question
stringlengths 11
28.2k
| answer
stringlengths 26
27.7k
| tag
stringclasses 130
values | question_id
int64 935
78.4M
| score
int64 10
5.49k
|
---|---|---|---|---|
I am writing some webservices returning JSON data, which have lots of users.
What are the benefits of using Nginx in front my server compared to just using the go http server?
| It depends.
Out of the box, putting nginx in front as a reverse proxy is going to give you:
Access logs
Error logs
Easy SSL termination
SPDY support
gzip support
Easy ways to set HTTP headers for certain routes in a couple of lines
Very fast static asset serving (if you're serving off S3/etc. though, this isn't that relevant)
The Go HTTP server is very good, but you will need to reinvent the wheel to do some of these things (which is fine: it's not meant to be everything to everyone).
I've always found it easier to put nginx in frontβwhich is what it is good atβand let it do the "web server" stuff. My Go application does the application stuff, and only the bare minimum of headers/etc. that it needs to. Don't look at putting nginx in front as a "bad" thing.
| NGINX | 17,776,584 | 107 |
I have several sets of static .html files on my server, and I would like use nginx to serve them directly. For example, nginx should serve an URI of the following pattern:
www.mysite.com/public/doc/foo/bar.html
with the .html file that is located at /home/www-data/mysite/public/doc/foo/bar.html. You can think of foo as the set name, and bar as the file name here.
I wonder whether the following piece of nginx config would do the job:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
alias /home/www-data/mysite/public/doc/;
}
location = /404.html {
alias /home/www-data/mysite/static/html/404.html;
}
}
In other words, all requests of the pattern /public/doc/.../....html are going to be handled by nginx, and if any given URI is not found, a default www.mysite.com/404.html is returned.
| It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directiveβs value:
it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
| NGINX | 12,806,893 | 106 |
I want to write some more complex conditions in my Nginx configuration files but I'm not sure of the syntax and can't find docs describing what you can do beyond the basics in the examples and I can't seem to find this on the Nginx forums or on the mailing list.
For example, is it possible for me to have an unless condition?
| So I'm a newbie to nginx, and had this same question. Turns out the syntax of the language as mentioned above is both custom and actually quite simple. The syntax is captured in a section in the NGINX docs, and repeated here for convenience:
nginx consists of modules which are controlled by directives
specified in the configuration file. Directives are divided into
simple directives and block directives. A simple directive consists of
the name and parameters separated by spaces and ends with a semicolon
(;). A block directive has the same structure as a simple directive,
but instead of the semicolon it ends with a set of additional
instructions surrounded by braces ({ and }). If a block directive can
have other directives inside braces, it is called a context (examples:
events, http, server, and location).
Directives placed in the configuration file outside of any contexts
are considered to be in the main context. The events and http
directives reside in the main context, server in http, and location in
server.
The rest of a line after the # sign is considered a comment.
In summary: Everything in an NGINX config file is a directive which may reference a variable. All directives are listed alphabetically here, and all variables are listed alphabetically here. NGINX configuration is driven by modules that each implement a certain piece of functionality, and each module contributes directives and variables that become available for use within the config. That's it.
That is why even if -- which looks like a keyword like in a traditional programming language -- is actually just a directive contributed by the ngx_http_rewrite_module module.
Hope this helps!
PS - Also check out https://devdocs.io/, and specifically https://devdocs.io/nginx, for a much improved way to search/use the NGINX documentation.
| NGINX | 2,936,260 | 103 |
I have a problem with nginx. I tried different solutions, but for me nothing work.
That is my error:
4 root@BANANAS ~ # sudo service nginx restart :(
Restarting nginx: nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] bind() to [::]:443 failed (98: Address already in use)
nginx: [emerg] still could not bind()
nginx.
Can you help me?
| Probably other process is using specified port:
sudo netstat -tulpn
Get the PID of the process that already using 443. And send signal with kill command.
sudo kill -2 <PID>
sudo service nginx restart
Aternatively you can do:
sudo fuser -k 443/tcp
Make sure you dont use old syntax:
server {
listen :80;
listen [::]:80;
}
The above syntax will cause
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
Correct syntax:
server {
listen 80;
listen [::]:80 ipv6only=on;
}
or
server {
listen [::]:80;
}
Both above syntax will achieve the same thing, listening on both ipv4 and ipv6.
| NGINX | 42,303,401 | 101 |
I have a Rails application that I want to deploy using Docker on an Ubuntu server. I have the Dockerfile for the application already set up, right now I want to view the nginx conf in its container.
I ran the command below to start an nginx container in an interactive mode:
docker run -i -t nginx:latest /bin/bash
Right now I am trying to install nano editor in order to view the configuration for nginx configuration (nginx.conf) using the commands below:
apt-get update
apt-get install nano
export TERM=xterm
However, when I run the first command apt-get update, I get the error below:
Err:1 http://security.debian.org/debian-security buster/updates InRelease
Temporary failure resolving 'security.debian.org'
Err:2 http://deb.debian.org/debian buster InRelease
Temporary failure resolving 'deb.debian.org'
Err:3 http://deb.debian.org/debian buster-updates InRelease
Temporary failure resolving 'deb.debian.org'
Reading package lists... Done
W: Failed to fetch http://deb.debian.org/debian/dists/buster/InRelease Temporary failure resolving 'deb.debian.org'
W: Failed to fetch http://security.debian.org/debian-security/dists/buster/updates/InRelease Temporary failure resolving 'security.debian.org'
W: Failed to fetch http://deb.debian.org/debian/dists/buster-updates/InRelease Temporary failure resolving 'deb.debian.org'
W: Some index files failed to download. They have been ignored, or old ones used instead.
I have checked very well it has nothing to do with network connectivity.
| Try restarting Docker.
One of these should work:
sudo service docker restart
sudo /etc/init.d/docker restart
sudo snap restart docker
Even in cases where Docker never worked before, some commenters said this was helpful.
| NGINX | 61,567,404 | 100 |
Is there any benchmark or comparison which is faster: place nginx in front of node and let it serve static files directly or use just node and serve static files using it?
nginx solution seems to be more manageable for me, any thoughts?
| I'll have to disagree with the answers here. While Node will do fine, nginx will most definitely be faster when configured correctly. nginx is implemented efficiently in C following a similar pattern (returning to a connection only when needed) with a tiny memory footprint. Moreover, it supports the sendfile syscall to serve those files which is as fast as you can possibly get at serving files, since it's the OS kernel itself that's doing the job.
By now nginx has become the de facto standard as the frontend server. You can use it for its performance in serving static files, gzip, SSL, and even load-balancing later on.
P.S.: This assumes that files are really "static" as in at rest on disk at the time of the request.
| NGINX | 9,967,887 | 100 |
I am using Laravel web framework on my ubuntu 14.04 server and Nginx web server, I have this error when I try to upload a file using Laravel to the server.
my upload directory is on the public/uploads folder that has 777 permission.
| The GD Graphics Library is for dynamically manipulating images.
For Ubuntu you should install it manually:
PHP8.0: sudo apt-get install php8.0-gd
PHP8.1: sudo apt-get install php8.1-gd
PHP8.2: sudo apt-get install php8.2-gd
PHP8.3: sudo apt-get install php8.3-gd
That's all, you can verify that GD support loaded:
php -i | grep -i gd
Output should be like this:
GD Support => enabled
GD headers Version => 2.1.1-dev
gd.jpeg_ignore_warning => 0 => 0
and finally restart your apache:
sudo service apache2 restart
| NGINX | 34,009,844 | 99 |
I'm new to NGINX and I'm trying to setup minimal working thing. So I trying to run aiohttp mini-app with nginx and supervisor (by this example). But I can't configure Nginx right and getting the following error:
nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/default:1
Here is full default.conf file:
http {
upstream aiohttp {
# Unix domain servers
server unix:/tmp/example_1.sock fail_timeout=0;
server unix:/tmp/example_2.sock fail_timeout=0;
server unix:/tmp/example_3.sock fail_timeout=0;
server unix:/tmp/example_4.sock fail_timeout=0;
}
server {
listen 80;
client_max_body_size 4G;
server example.com;
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
proxy_buffering off;
proxy_pass http://aiohttp;
}
}
}
It looks correct. server directive is in http as it should be. And http is parent directive. What I'm doing wrong?
| I am assuming that you have http in your /etc/nginx/nginx.conf file which then tells nginx to include sites-enabled/*;
So then you have
http
http
server
As the http directive should only happen once just remove the http directive from your sites-enabled config file(s)
| NGINX | 43,643,829 | 97 |
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
if (-f $request_filename) {
access_log off;
expires 30d;
break;
}
if (!-f $request_filename) {
proxy_pass http://127.0.0.1:8080; # backend server listening
break;
}
}
Above will serve all existing files directly using Nginx (e.g. Nginx just displays PHP source code), otherwise forward a request to Apache. I need to exclude *.php files from the rule so that requests for *.php are also passed to Apache and processed.
I want Nginx to handle all static files and Apache to process all dynamic stuff.
EDIT: There is white list approach, but it is not very elegant, See all those extensions, I don't want this.
location ~* ^.+.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$ {
access_log off;
expires 30d;
}
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
EDIT 2: On newer versions of Nginx use try_files instead http://wiki.nginx.org/HttpCoreModule#try_files
| Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.
location / {
root /path/to/root/of/static/files;
try_files $uri $uri/ @apachesite;
expires max;
access_log off;
}
location @apachesite {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.
| NGINX | 869,001 | 97 |
I am using Nginx in front of 10 mongrels.
When I make a request with size larger then 2900 I get back an:
error code 414: uri too large
Does anyone know the setting in the nginx configuration file which determines the allowed uri length ?
| From: http://nginx.org/r/large_client_header_buffers
Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server
Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.
so you need to change the size parameter at the end of that line to something bigger for your needs.
| NGINX | 1,067,334 | 96 |
I uploaded react.js application to a server. I'm using nginx server. Application is working fine. But when I go to another page & refresh, the site is not working. It's showing a 404 Not found error.
How can I solve this?
| When your react.js app loads, the routes are handled on the frontend by the react-router. Say for example you are at http://a.com. Then on the page you navigate to http://a.com/b. This route change is handled in the browser itself. Now when you refresh or open the url http://a.com/b in the a new tab, the request goes to your nginx where the particular route does not exist and hence you get 404.
To avoid this, you need to load the root file(usually index.html) for all non matching routes so that nginx sends the file and the route is then handled by your react app on the browser. To do this you have to make the below change in your nginx.conf or sites-enabled appropiately
location / {
try_files $uri /index.html;
}
This tells nginx to look for the specified $uri, if it cannot find one then it send index.html back to the browser. (See https://serverfault.com/questions/329592/how-does-try-files-work for more details)
| NGINX | 43,555,282 | 95 |
Update II
It's now July 16th, 2015 and things have changed again. I've discovered this automagical container from Jason Wilder: https://github.com/jwilder/nginx-proxy and it solves this problem in about as long as it takes to docker run the container. This is now the solution I'm using to solve this problem.
Update
It's now July of 2015 and things have change drastically with regards to networking Docker containers. There are now many different offerings that solve this problem (in a variety of ways).
You should use this post to gain a basic understanding of the docker --link approach to service discovery, which is about as basic as it gets, works very well, and actually requires less fancy-dancing than most of the other solutions. It is limited in that it's quite difficult to network containers on separate hosts in any given cluster, and containers cannot be restarted once networked, but does offer a quick and relatively easy way to network containers on the same host. It's a good way to get an idea of what the software you'll likely be using to solve this problem is actually doing under the hood.
Additionally, you'll probably want to also check out Docker's nascent network, Hashicorp's consul, Weaveworks weave, Jeff Lindsay's progrium/consul & gliderlabs/registrator, and Google's Kubernetes.
There's also the CoreOS offerings that utilize etcd, fleet, and flannel.
And if you really want to have a party you can spin up a cluster to run Mesosphere, or Deis, or Flynn.
If you're new to networking (like me) then you should get out your reading glasses, pop "Paint The Sky With Stars β The Best of Enya" on the Wi-Hi-Fi, and crack a beer β it's going to be a while before you really understand exactly what it is you're trying to do. Hint: You're trying to implement a Service Discovery Layer in your Cluster Control Plane. It's a very nice way to spend a Saturday night.
It's a lot of fun, but I wish I'd taken the time to educate myself better about networking in general before diving right in. I eventually found a couple posts from the benevolent Digital Ocean Tutorial gods: Introduction to Networking Terminology and Understanding ... Networking. I suggest reading those a few times first before diving in.
Have fun!
Original Post
I can't seem to grasp port mapping for Docker containers. Specifically how to pass requests from Nginx to another container, listening on another port, on the same server.
I've got a Dockerfile for an Nginx container like so:
FROM ubuntu:14.04
MAINTAINER Me <[email protected]>
RUN apt-get update && apt-get install -y htop git nginx
ADD sites-enabled/api.myapp.com /etc/nginx/sites-enabled/api.myapp.com
ADD sites-enabled/app.myapp.com /etc/nginx/sites-enabled/app.myapp.com
ADD nginx.conf /etc/nginx/nginx.conf
RUN echo "daemon off;" >> /etc/nginx/nginx.conf
EXPOSE 80 443
CMD ["service", "nginx", "start"]
And then the api.myapp.com config file looks like so:
upstream api_upstream{
server 0.0.0.0:3333;
}
server {
listen 80;
server_name api.myapp.com;
return 301 https://api.myapp.com/$request_uri;
}
server {
listen 443;
server_name api.mypp.com;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_pass http://api_upstream;
}
}
And then another for app.myapp.com as well.
And then I run:
sudo docker run -p 80:80 -p 443:443 -d --name Nginx myusername/nginx
And it all stands up just fine, but the requests are not getting passed-through to the other containers/ports. And when I ssh into the Nginx container and inspect the logs I see no errors.
Any help?
| @T0xicCode's answer is correct, but I thought I would expand on the details since it actually took me about 20 hours to finally get a working solution implemented.
If you're looking to run Nginx in its own container and use it as a reverse proxy to load balance multiple applications on the same server instance then the steps you need to follow are as such:
Link Your Containers
When you docker run your containers, typically by inputting a shell script into User Data, you can declare links to any other running containers. This means that you need to start your containers up in order and only the latter containers can link to the former ones. Like so:
#!/bin/bash
sudo docker run -p 3000:3000 --name API mydockerhub/api
sudo docker run -p 3001:3001 --link API:API --name App mydockerhub/app
sudo docker run -p 80:80 -p 443:443 --link API:API --link App:App --name Nginx mydockerhub/nginx
So in this example, the API container isn't linked to any others, but the
App container is linked to API and Nginx is linked to both API and App.
The result of this is changes to the env vars and the /etc/hosts files that reside within the API and App containers. The results look like so:
/etc/hosts
Running cat /etc/hosts within your Nginx container will produce the following:
172.17.0.5 0fd9a40ab5ec
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3 App
172.17.0.2 API
ENV Vars
Running env within your Nginx container will produce the following:
API_PORT=tcp://172.17.0.2:3000
API_PORT_3000_TCP_PROTO=tcp
API_PORT_3000_TCP_PORT=3000
API_PORT_3000_TCP_ADDR=172.17.0.2
APP_PORT=tcp://172.17.0.3:3001
APP_PORT_3001_TCP_PROTO=tcp
APP_PORT_3001_TCP_PORT=3001
APP_PORT_3001_TCP_ADDR=172.17.0.3
I've truncated many of the actual vars, but the above are the key values you need to proxy traffic to your containers.
To obtain a shell to run the above commands within a running container, use the following:
sudo docker exec -i -t Nginx bash
You can see that you now have both /etc/hosts file entries and env vars that contain the local IP address for any of the containers that were linked. So far as I can tell, this is all that happens when you run containers with link options declared. But you can now use this information to configure nginx within your Nginx container.
Configuring Nginx
This is where it gets a little tricky, and there's a couple of options. You can choose to configure your sites to point to an entry in the /etc/hosts file that docker created, or you can utilize the ENV vars and run a string replacement (I used sed) on your nginx.conf and any other conf files that may be in your /etc/nginx/sites-enabled folder to insert the IP values.
OPTION A: Configure Nginx Using ENV Vars
This is the option that I went with because I couldn't get the
/etc/hosts file option to work. I'll be trying Option B soon enough
and update this post with any findings.
The key difference between this option and using the /etc/hosts file option is how you write your Dockerfile to use a shell script as the CMD argument, which in turn handles the string replacement to copy the IP values from ENV to your conf file(s).
Here's the set of configuration files I ended up with:
Dockerfile
FROM ubuntu:14.04
MAINTAINER Your Name <[email protected]>
RUN apt-get update && apt-get install -y nano htop git nginx
ADD nginx.conf /etc/nginx/nginx.conf
ADD api.myapp.conf /etc/nginx/sites-enabled/api.myapp.conf
ADD app.myapp.conf /etc/nginx/sites-enabled/app.myapp.conf
ADD Nginx-Startup.sh /etc/nginx/Nginx-Startup.sh
EXPOSE 80 443
CMD ["/bin/bash","/etc/nginx/Nginx-Startup.sh"]
nginx.conf
daemon off;
user www-data;
pid /var/run/nginx.pid;
worker_processes 1;
events {
worker_connections 1024;
}
http {
# Basic Settings
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 33;
types_hash_max_size 2048;
server_tokens off;
server_names_hash_bucket_size 64;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging Settings
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# Gzip Settings
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 3;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/xml text/css application/x-javascript application/json;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
# Virtual Host Configs
include /etc/nginx/sites-enabled/*;
# Error Page Config
#error_page 403 404 500 502 /srv/Splash;
}
NOTE: It's important to include daemon off; in your nginx.conf file to ensure that your container doesn't exit immediately after launching.
api.myapp.conf
upstream api_upstream{
server APP_IP:3000;
}
server {
listen 80;
server_name api.myapp.com;
return 301 https://api.myapp.com/$request_uri;
}
server {
listen 443;
server_name api.myapp.com;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_pass http://api_upstream;
}
}
Nginx-Startup.sh
#!/bin/bash
sed -i 's/APP_IP/'"$API_PORT_3000_TCP_ADDR"'/g' /etc/nginx/sites-enabled/api.myapp.com
sed -i 's/APP_IP/'"$APP_PORT_3001_TCP_ADDR"'/g' /etc/nginx/sites-enabled/app.myapp.com
service nginx start
I'll leave it up to you to do your homework about most of the contents of nginx.conf and api.myapp.conf.
The magic happens in Nginx-Startup.sh where we use sed to do string replacement on the APP_IP placeholder that we've written into the upstream block of our api.myapp.conf and app.myapp.conf files.
This ask.ubuntu.com question explains it very nicely:
Find and replace text within a file using commands
GOTCHA
On OSX, sed handles options differently, the -i flag specifically.
On Ubuntu, the -i flag will handle the replacement 'in place'; it
will open the file, change the text, and then 'save over' the same
file.
On OSX, the -i flag requires the file extension you'd like the resulting file to have. If you're working with a file that has no extension you must input '' as the value for the -i flag.
GOTCHA
To use ENV vars within the regex that sed uses to find the string you want to replace you need to wrap the var within double-quotes. So the correct, albeit wonky-looking, syntax is as above.
So docker has launched our container and triggered the Nginx-Startup.sh script to run, which has used sed to change the value APP_IP to the corresponding ENV variable we provided in the sed command. We now have conf files within our /etc/nginx/sites-enabled directory that have the IP addresses from the ENV vars that docker set when starting up the container. Within your api.myapp.conf file you'll see the upstream block has changed to this:
upstream api_upstream{
server 172.0.0.2:3000;
}
The IP address you see may be different, but I've noticed that it's usually 172.0.0.x.
You should now have everything routing appropriately.
GOTCHA
You cannot restart/rerun any containers once you've run the initial instance launch. Docker provides each container with a new IP upon launch and does not seem to re-use any that its used before. So api.myapp.com will get 172.0.0.2 the first time, but then get 172.0.0.4 the next time. But Nginx will have already set the first IP into its conf files, or in its /etc/hosts file, so it won't be able to determine the new IP for api.myapp.com. The solution to this is likely to use CoreOS and its etcd service which, in my limited understanding, acts like a shared ENV for all machines registered into the same CoreOS cluster. This is the next toy I'm going to play with setting up.
OPTION B: Use /etc/hosts File Entries
This should be the quicker, easier way of doing this, but I couldn't get it to work. Ostensibly you just input the value of the /etc/hosts entry into your api.myapp.conf and app.myapp.conf files, but I couldn't get this method to work.
UPDATE:
See @Wes Tod's answer for instructions on how to make this method work.
Here's the attempt that I made in api.myapp.conf:
upstream api_upstream{
server API:3000;
}
Considering that there's an entry in my /etc/hosts file like so: 172.0.0.2 API I figured it would just pull in the value, but it doesn't seem to be.
I also had a couple of ancillary issues with my Elastic Load Balancer sourcing from all AZ's so that may have been the issue when I tried this route. Instead I had to learn how to handle replacing strings in Linux, so that was fun. I'll give this a try in a while and see how it goes.
| NGINX | 27,912,917 | 95 |
I use SetEnv in Apache to set some variables in virtualhosts that I recover in PHP using $_SERVER[the_variable].
Now I am switching to Perl Catalyst and Nginx, but it seems that the "env" directive in Nginx is not the same. It does not work. How can it be accomplished?
Here is the background picture, just in case someone can suggest a better approach or my previous system does not work with Nginx.
I use the same app for many domains. All data comes from different databases with the same structure.
The database name is hardcoded to the virtual host, in that environmental variable.
As I know the database name, all the queries go to its appropriate database, from the very first query.
I can have multiple domains using the same database, just including the same variable into the directives.
| location / {
...
fastcgi_param APPLICATION_ENV production;
fastcgi_param APPLICATION_CONFIG user;
...
}
but it's for PHP-CGI
| NGINX | 8,098,927 | 95 |
I have my config setup to handle a bunch of GET requests which render pixels that work fine to handle analytics and parse query strings for logging. With an additional third party data stream, I need to handle a POST request to a given url that has JSON in an expected loggable format inside of it's request body. I don't want to use a secondary server with proxy_pass and just want to log the whole response into an associated log file like what it does with GET requests. A snippet of some code that I'm using looks like the following:
GET request (which works great):
location ^~ /rl.gif {
set $rl_lcid $arg_lcid;
if ($http_cookie ~* "lcid=(.*\S)")
{
set $rl_lcid $cookie_lcid;
}
empty_gif;
log_format my_tracking '{ "guid" : "$rl_lcid", "data" : "$arg__rlcdnsegs" }';
access_log /mnt/logs/nginx/my.access.log my_tracking;
rewrite ^(.*)$ http://my/url?id=$cookie_lcid? redirect;
}
Here is kinda what I am trying to do:
POST request (which does not work):
location /bk {
log_format bk_tracking $request_body;
access_log /mnt/logs/nginx/bk.access.log bk_tracking;
}
Curling curl http://myurl/bk -d name=example gives me a 404 page not found.
Then I tried:
location /bk.gif {
empty_gif;
log_format bk_tracking $request_body;
access_log /mnt/logs/nginx/bk.access.log bk_tracking;
}
Curling curl http://myurl/bk.gif -d name=example gives me a 405 Not Allowed.
My current version is nginx/0.7.62. Any help in the right direction is very much appreciated! Thanks!
UPDATE
So now my post looks like this:
location /bk {
if ($request_method != POST) {
return 405;
}
proxy_pass $scheme://127.0.0.1:$server_port/dummy;
log_format my_tracking $request_body;
access_log /mnt/logs/nginx/my.access.log my_tracking;
}
location /dummy { set $test 0; }
It is logging the post data correctly, but returns a 404 on the requesters end. If I change the above code to return a 200 like so:
location /bk {
if ($request_method != POST) {
return 405;
}
proxy_pass $scheme://127.0.0.1:$server_port/dummy;
log_format my_tracking $request_body;
access_log /mnt/logs/nginx/my.access.log my_tracking;
return 200;
}
location /dummy { set $test 0; }
Then it return the 200 correctly, but no longer records the post data.
ANOTHER UPDATE
Kinda found a working solution. Hopefully this can help other on their way.
| This solution works like a charm:
http {
log_format postdata $request_body;
server {
location = /post.php {
access_log /var/log/nginx/postdata.log postdata;
fastcgi_pass php_cgi;
}
}
}
I think the trick is making nginx believe that you will call a CGI script.
Edit 2022-03-15: there is some discussion on where log_format should be set. The documentation clearly says that it needs to be in the http context: http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format
If you put log_format in the server context, nginx will fail to load the config: nginx: [emerg] "log_format" directive is not allowed here in <path>:<line> (tested with nginx 1.20 on ubuntu 18.04)
| NGINX | 4,939,382 | 95 |
I'd love to use nginx to serve a website with multiple domain names and SSL:
webmail.example.com
webmail.beispiel.de
Both use the same vhost so I only set the server_name twice.
Problem is, that I need nginx to serve the correct ssl certificate for each domain name.
Is this possible with one vhost or do I need to set up two vhosts?
| Edit November 2014: the initial answer is not correct and is incomplete ; it needed a refresh! here it is.
Basically, there are two cases
You own a wildcard certificate (or multi-domains certificate)
In this case, you may use several vhosts listening to the same IP address/https port, and both vhosts use the same certificate (listening on all interfaces), e.g.
server {
listen 443;
server_name webmail.example.com;
root /var/www/html/docs/sslexampledata;
ssl on;
ssl_certificate /var/www/ssl/samecertif.crt;
ssl_certificate_key /var/www/ssl/samecertif.key;
...
}
server {
listen 443;
server_name webmail.beispiel.de;
root /var/www/html/docs/sslbeispieldata;
ssl on;
ssl_certificate /var/www/ssl/samecertif.crt;
ssl_certificate_key /var/www/ssl/samecertif.key;
...
}
or in you specific case, having both domains served by the same data
server {
listen 443;
server_name webmail.example.com webmail.beispiel.de; # <== 2 domains
root /var/www/html/docs/sslbeispieldata;
ssl on;
ssl_certificate /var/www/ssl/samecertif.crt;
ssl_certificate_key /var/www/ssl/samecertif.key;
...
}
You have two(+) different certificates
The case above (one IP for all certificates) will still work with modern browsers via Server Name Indication. SNI has the client (browser) send the host it wants to reach in the request header, allowing the server (nginx) to deal with vhosts before having to deal with the certificate. The configuration is the same as above, except that each vhost has a specific certificate, crt and key.
(nginx support SNI from 0.9.8f, check your nginx server is SNI compliant)
(also, SF talks about SNI and browser support)
Otherwise, if you want to reach older browsers as well, you need several vhosts listening each to a different IP addresses/https ports, e.g.
server {
listen 1.2.3.4:443; # <== IP 1.2.3.4
server_name webmail.example.com;
root /var/www/html/docs/sslexampledata;
ssl on;
ssl_certificate /var/www/ssl/certifIP1example.crt;
ssl_certificate_key /var/www/ssl/certifIP1example.key;
...
}
server {
listen 101.102.103:443; <== different IP
server_name webmail.beispiel.de;
root /var/www/html/docs/sslbeispieldata;
ssl on;
ssl_certificate /var/www/ssl/certifIP2beispiel.crt;
ssl_certificate_key /var/www/ssl/certifIP2beispiel.key;
...
}
The reason is well explained here.
| NGINX | 14,434,120 | 93 |
I'm installing a previously built website on a new server. I'm not the original developer.
I've used Gunicorn + nginx in the past to keep the app alive (basically following this tutorial), but am having problems with it here.
I source venv/bin/activate, then ./manage.py runserver 0.0.0.0:8000 works well and everything is running as expected. I shut it down and run gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application, and get the following:
[2016-09-13 01:11:47 +0000] [15259] [INFO] Starting gunicorn 19.6.0
[2016-09-13 01:11:47 +0000] [15259] [INFO] Listening at: http://0.0.0.0:8000 (15259)
[2016-09-13 01:11:47 +0000] [15259] [INFO] Using worker: sync
[2016-09-13 01:11:47 +0000] [15262] [INFO] Booting worker with pid: 15262
[2016-09-13 01:11:47 +0000] [15262] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
worker.init_process()
File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process
self.load_wsgi()
File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
self.wsgi = self.app.wsgi()
File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
return self.load_wsgiapp()
File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
return util.import_app(self.app_uri)
File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app
__import__(module)
ImportError: No module named 'myproject.wsgi'
[2016-09-13 01:11:47 +0000] [15262] [INFO] Worker exiting (pid: 15262)
[2016-09-13 01:11:47 +0000] [15259] [INFO] Shutting down: Master
[2016-09-13 01:11:47 +0000] [15259] [INFO] Reason: Worker failed to boot.
I believe it has something to do with the structure of the whole application. Before, I've built apps with the basic structure of:
myproject
βββ manage.py
βββ myproject
βΒ Β βββ urls.py
βΒ Β βββ views.py
βΒ Β βββ component1
β βΒ Β βββ urls.py
β βΒ Β βββ views.py
βΒ Β βββ component2
β βΒ Β βββ urls.py
β βΒ Β βββ views.py
βββ venv
βΒ Β βββ bin
βΒ Β βββ ...
This one, instead, has a structure like:
myproject
βββ apps
βΒ Β βββ blog
β βΒ Β βββ urls.py
β βΒ Β βββ views.py
βΒ Β β βββ ...
βΒ Β βββ catalogue
β βΒ Β βββ urls.py
β βΒ Β βββ views.py
βΒ Β β βββ ...
βΒ Β βββ checkout
β βΒ Β βββ urls.py
β βΒ Β βββ views.py
βΒ Β β βββ ...
βΒ Β βββ core
β βΒ Β βββ urls.py
β βΒ Β βββ views.py
βΒ Β β βββ ...
βΒ Β βββ customer
βΒ Β βββ dashboard
βΒ Β βββ __init__.py
βββ __init__.py
βββ manage.py
βββ project_static
βΒ Β βββ assets
βΒ Β βββ bower_components
βΒ Β βββ js
βββ public
βΒ Β βββ emails
βΒ Β βββ media
βΒ Β βββ static
βββ settings
βΒ Β βββ base.py
βΒ Β βββ dev.py
βΒ Β βββ __init__.py
βΒ Β βββ local.py
βΒ Β βββ production.py
βββ templates
βΒ Β βββ base.html
βΒ Β βββ basket
βΒ Β βββ blog
βΒ Β βββ ....
βββ urls.py
βββ venv
βΒ Β βββ bin
βΒ Β βββ include
βΒ Β βββ lib
βΒ Β βββ pip-selfcheck.json
βΒ Β βββ share
βββ wsgi.py
So, there's no 'main' module running the show, which is what I expect gunicorn is looking for.
Any thoughts?
wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
application = get_wsgi_application()
| Your error message is
ImportError: No module named 'myproject.wsgi'
You ran the app with
gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application
And wsgi.py has the line
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
This is the disconnect. In order to recognize the project as myproject.wsgi the parent directory would have to be on the python path... running
cd .. && gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application
Would eliminate that error. However, you would then get a different error because the wsgi.py file refers to settings instead of myproject.settings. This implies that the app was intended to be run from the root directory instead of one directory up. You can figure this out for sure by looking at the code- if it uses absolute imports, do they usually say from myproject.app import ... or from app import .... If that guess is correct, your correct commmand is
gunicorn --bind 0.0.0.0:8000 wsgi:application
If the app does use myproject in all of the paths, you'll have to modify your PYTHONPATH to run it properly...
PYTHONPATH=`pwd`/.. gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application
| NGINX | 39,460,892 | 92 |
Trying to deploy my first portal .
I am getting 502 gateway timeout error in browser when i was sending the request through browser
when i checked the logs , i got this error
2014/02/03 09:00:32 [error] 16607#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 14.159.131.19, server: foo.com, request: "GET HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "22.11.180.154"
is there any problem related to permissions
| I don't think that solution would work anyways because you will see some error message in your error log file.
The solution was a lot easier than what I thought.
simply, open the following path to your php5-fpm
sudo nano /etc/php5/fpm/pool.d/www.conf
or if you're the admin 'root'
nano /etc/php5/fpm/pool.d/www.conf
Then find this line and uncomment it:
listen.allowed_clients = 127.0.0.1
This solution will make you be able to use listen = 127.0.0.1:9000 in your vhost blocks
like this: fastcgi_pass 127.0.0.1:9000;
after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm
Php5-fpm
sudo service php5-fpm restart
or
sudo service php5-fpm reload
Nginx
sudo service nginx restart
or
sudo service nginx reload
From the comments:
Also comment
;listen = /var/run/php5-fpm.sock
and add
listen = 9000
| NGINX | 21,524,373 | 92 |
I'm using Nginx as a proxy to filter requests to my application. With the help of the "http_geoip_module" I'm creating a country code http-header, and I want to pass it as a request header using "headers-more-nginx-module". This is the location block in the Nginx configuration:
location / {
proxy_pass http://mysite.com;
proxy_set_header Host http://mysite.com;;
proxy_pass_request_headers on;
more_set_headers 'HTTP_Country-Code: $geoip_country_code';
}
But this only sets the header in the response. I tried using "more_set_input_headers" instead of "more_set_headers" but then the header isn't even passed to the response.
What am I missing here?
| If you want to pass the variable to your proxy backend, you have to set it with the proxy module.
location / {
proxy_pass http://example.com;
proxy_set_header Host example.com;
proxy_set_header HTTP_Country-Code $geoip_country_code;
proxy_pass_request_headers on;
}
And now it's passed to the proxy backend.
| NGINX | 19,751,313 | 92 |
What regular expression engine does Nginx use? There are a lot of possibilities. More to the point, what flavor of syntax does it support, that is, what syntax features can I make use of?
| Nginx uses the PCRE library. The compile-time options list has some notes on this.
| NGINX | 14,126,872 | 92 |
This is my first web-server administration experience and I want to build docker container which uses nginx as a web-server. In all docker tutorial daemon off; option is put into main .conf file but explanation about it is omitted.
I search on the internet about it and I don't understand what is the difference between daemon on; and daemon off; options. Some people mentioned that daemon off; is for production, why?
Can you explain, what is the difference between this two options, and why I should use daemon off; on production?
| For normal production (on a server), use the default daemon on; directive so the Nginx server will start in the background. In this way Nginx and other services are running and talking to each other. One server runs many services.
For Docker containers (or for debugging), the daemon off; directive tells Nginx to stay in the foreground. For containers this is useful as best practice is for one container = one process. One server (container) has only one service.
Setting daemon off; is also useful if there's a 3rd party tool like Supervisor controlling your services. Supervisor lets you stop/start/get status for bunches of services at once.
I use daemon off; for tweaking my Nginx config, then cleanly killing the service and restarting it. This lets me test configurations rapidly. When done I use the default daemon on;.
| NGINX | 25,970,711 | 91 |
All JavaScript files are not compressed by nginx gzip.
CSS files are working.
In my nginx.conf I have the following lines:
gzip on;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
gzip_proxied any;
gzip_buffers 16 8k;
gzip_types text/plain application/x-javascript text/xml text/css;
gzip_vary on;
| Change this line:
gzip_types text/plain application/x-javascript text/xml text/css;
To be this:
gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
Note the addition of application/javascript and text/javascript to your list of gzip types.
There are also more detailsβand a more expansive list of gzip typesβin the answer posted here.
| NGINX | 23,939,722 | 91 |
I want to run a shell script every time my nginx server receives any HTTP request. Any simple ways to do this?
| You can execute a shell script via Lua code from the nginx.conf file to achieve this. You need to have the HttpLuaModule to be able to do this.
Here's an example to do this.
location /my-website {
content_by_lua_block {
os.execute("/bin/myShellScript.sh")
}
}
| NGINX | 22,891,148 | 91 |
I'm trying to test my React application on a mobile device. I'm using ngrok to make my local server available to other devices and have gotten this working with a variety of other applications. However, when I try to connect ngrok to the React dev server, I get the error:
Invalid Host Header
I believe that React blocks all requests from another source by default. Any thoughts?
| I'm encountering a similar issue and found two solutions that work as far as viewing the application directly in a browser
ngrok http 8080 --host-header="localhost:8080"
ngrok http --host-header=rewrite 8080
obviously, replace 8080 with whatever port you're running on
this solution still raises an error when I use this in an embedded page, that pulls the bundle.js from the react app. I think since it rewrites the header to localhost when this is embedded, it's looking to localhost, which the app is no longer running on
| ngrok | 45,425,721 | 370 |
From previous versions of the question, there is this: Browse website with ip address rather than localhost, which outlines pretty much what I've done so far...I've got the local IP working. Then I found ngrok, and apparently I don't need to connect via the IP.
What I am trying to do is expose my website running on localhost to the internet. I found a tool that will do this: ngrok.
Running the website in visual studio, the website starts up on localhost/port#. I run the command "ngrok http port#" in the command line. Everything seems to start up fine. I generate a couple of URLs, and the ngrok inspection url (localhost:4040) works.
The only problem is that when I go to the generated URLs, I get an HTTP error 400: bad request invalid hostname. This is a different error than when I run "ngrok http wrongport#", which is a host not found error...so I think something good is happening. I just can't tell what...
Is there a step I am missing in exposing my site to the internet via the tunneling service? If there is, I can't find it in the ngrok documentation.
| Troubleshot this issue with ngrok. In the words of inconshrevable, some applications get angry when they see a different host header than expected.
Running the following command should fix the problem:
ngrok http [port] --host-header="localhost:[port]"
Depending on the version, you may also want to try:
ngrok http [port] --host-header="localhost:[port]"
| ngrok | 30,535,336 | 297 |
Is it possible to open multiples ports in ngrok in same domain?
Something like:
Fowarding http://example.ngrok.com:50001 -> 127.0.0.1:50001
Fowarding http://example.ngrok.com:50002 -> 127.0.0.1:50002
IΒ΄m working in windows and it'll be useful for debuging with IIS Express
| Yes, it is possible using multiple simultaneous tunnels, within the same hostname !
All you need to do, is to declare them on your configuration file, like this:
authtoken: 4nq9771bPxe8ctg7LKr_2ClH7Y15Zqe4bWLWF9p
tunnels:
first-app:
addr: 50001
proto: http
hostname: example.ngrok.com
host_header: first-app.example.ngrok.com
second-app:
addr: 50002
proto: http
hostname: example.ngrok.com
host_header: second-app.example.ngrok.com
And run them with:
ngrok start --all
Look on the documentation for options, like hostname, subdomain, authtoken and host_header. Hope this help you !
P.S For Free plan remove custom host and header part
like this it will be different domains FYI.
authtoken: 6yMXA63qefMZqCWSCHaaYq_5LufcciP1rG4LCZETjC6V
tunnels:
first:
addr: 3002
proto: http
second:
addr: 8080
proto: http
NOTES:
To find your default config file read https://ngrok.com/docs/ngrok-agent/config/.
All plans issues an auth token. You can find yours in the web dashboard: https://dashboard.ngrok.com/get-started
| ngrok | 25,522,360 | 137 |
When I start an ngrok client with ./ngrok tcp 22 it runs in the foreground and I can see the randomly generated forwarding URL, such as tcp://0.tcp.ngrok.io:12345 -> localhost:22.
If I run in it the background with ./ngrok tcp &, I can't find any way to see the forwarding URL. How can I run ngrok in the background and still see the URL?
| There are a couple of ways.
You can either:
1) Visit localhost:4040/status in your browser to see a bunch of information, or
2) Use curl to hit the API: localhost:4040/api/tunnels
| ngrok | 34,322,988 | 58 |
I tried running ngrok in the background with following command:
./ngrok -subdomain test -config=ngrok.cfg 80 &
the process is running:
[1] 3866
and the subdomain doesn't work.
It works with:
./ngrok -subdomain test -config=ngrok.cfg 80
Does anyone know what is going wrong here?
Thank you.
| as described previously you can run ngrok in background with
./ngrok http 8080 > /dev/null &
next you can use curl and for example jq a command-line JSON processor.
export WEBHOOK_URL="$(curl http://localhost:4040/api/tunnels | jq ".tunnels[0].public_url")"
your URL will be accessible from $WEBHOOK_URL env variable and you can use it anywhere.
| ngrok | 27,162,552 | 38 |
I use mamp and I have virtual hosts all on port 8888. For example:
site1.dev:8888
site2.dev:8888
would point to localhost/site1/, localhost/site2/ etc.
Before using virtual hosts, I would just change my docroot to whatever project I was currently working on and would start ngrok like so
./ngrok http 8888 and it would launch and give me a random generated *.ngrok.io url.
My question is how do I specify the domain now since I am using virtual hosts?
I've tried ./ngrok http site1.dev:8888 and it starts but just serves up mamps webroot.
I am using a free account.
| If you prefer a free option, it is possible via:
ngrok http --host-header=site1.dev 80
| ngrok | 35,138,017 | 38 |
Is it possible to host, instead of a web app, a HTML file with NGROK? I really don't know anything about NGROK, I just used it to host a server for a Twilio app, and am wanting to use it to host a HTML file for another one of my projects. Also, anybody know how to create a HTML file on a Mac? Thanks in advance. Or, If I can't use NGROK, anybody know something as easy and free is it is that I could use for hosting a HTML file on my computer. I need to be able to change the file in real time, so google sites and stuff like that are out of the question.
| No. ngrok only tunnels traffic, so it can't actually serve the HTML file for you.
You can, however, serve a directory of files very easily. One of the quickest ways to start a server is with python. From the command line, cd to the directory containing your HTML files and run:
$ python3 -m http.server
Or for python 2:
$ python -m SimpleHTTPServer
Then, in another terminal, run ngrok.
| ngrok | 23,438,032 | 35 |
The remote Linux computer is in an internal network and has no public IP address. So I installed ngrok.
ngrok tcp 22
ngrok by @inconshreveable (Ctrl+C to quit)
Tunnel Status online
Version 2.0.19/2.0.17
Web Interface http://127.0.0.1:4040
Forwarding tcp://0.tcp.ngrok.io:36428 ->
localhost:22
Connections ttl opn rt1 rt5 p50 p90
0 0 0.00 0.00 0.00 0.00
I checked that sshd is running.
At the local PC, I tried
ssh [email protected] -p36428
which gave rise to
ssh: connect to host ngrok.com port 36428: Connection refused
| You are connecting to the wrong destination address. The command should be
ssh [email protected] -p36428
Notice the different hostname (ie 0.tcp.ngrok.io instead of ngrok.com).
And generally you would want to put the user@hostname after all the options (eg -p36428), even though it doesn't generally cause any issues.
| ngrok | 30,577,729 | 29 |
Objective: want to share a website preview using ngrok, which creates a tunnel from which my localhost can be seen with an url of something like mywebsite.ngrok.io
Problem: I use WAMP and my localhost folder looks something like this:
localhostdirectory
|-- website1
|-- website2
|-- etc
To access a website I type to localhost/website1/ in the browser, I would like to tunnel only that URL, the possible solutions would be:
Setting up a Virtual host, I would go through the hassle of manually setting up a virtual host, then I get something like website1.dev, and then I would pass it to ngrok as the host header in the HTTP request, like that:
ngrok http -host-header=website1.dev 80
I didn't understand what the host header is though, and why can't I pass a relative url like localhost/website1/, also what is the rewrite option?
Change the folder directory of my localhost to the folder of the website, I would prefer not to do that.
Is there a better way to accomplish my objective in an easier way, maybe going through WAMP aliases?
| If you make do with Apache Vhost you just have to exec command
ngrok http -host-header=rewrite YOUR-LOCAL-DOMAIN:PORT
Dont forgot to edit host file for resolution @IP <-> YOUR-LOCAL-DOMAIN
| ngrok | 30,017,319 | 27 |
i have an angular app running on localhost with port 80, when i use ngrok http 80 command it shows invalid host header. how to use ngrok to work with my angular 4?
| if your local angular webapp runs at port 80, run:
ngrok http --host-header=rewrite 80
Note: ngrok should be added to your PATH
| ngrok | 44,755,464 | 23 |
I'm using ngrok to put my web application online and make some tests. But, when I reload the page, the error ERR_NGROK_702 (Too Many Connections) appears, like the image below.
Is there any way to solve or avoid it instead of buying a paid plan?
How can I decrease the inbound connection volume, as said in the message?
Or the only way is to wait some minutes and try again?
I'll appreciate any suggestions.
| You can use https://github.com/mmatczuk/go-http-tunnel it's self hosted open source ngrok alternative.
| ngrok | 40,939,587 | 20 |
I have ngrok running on a server I remote into.
I start it by using the obvious, ngrok.exe http 80. The problem is that when I sign off on that particular server, ngrok will close out and I will lose my tunnel. Is there a way I can keep the ngrok tunnel running even when I have signed off the machine? I understand if the machine is shut down there is nothing I can do to keep the tunnel running, that is obvious. Any ideas?
Thanks in advance.
| As you've said If the machine is shutdown there will be no way keep the process running. There are a number of methods to do this. In each of these methods I'm assuming you already have the following config file:
config.yml
authtoken: <your-auth-token>
tunnels:
default:
proto: http
addr: 80
Ngrok Link (Windows/Mac OS/Linux, Commercial)
With ngrok link simply run the following commands:
ngrok service install -config /path/to/your/config.yml
ngrok service start
You should then be able to manage ngrok as you would any other service running on your given operating system.
Nohup (Maco OS/Linux)
The nohup command normally comes installed by default on mac os and linux. To run the command as such:
nohup ngrok start --all --config="path/to/config.yml" &
Running in a screen should also achieve the same effect here.
Creating a Windows Service (Windows)
To create the service you will need to download a program for creating services from non service executables. Here I'm going to how to do this with NSSM (Non-Sucking Service Manager).
Download the executable
Open CMD and cd into the same directory as the nssm.exe
Run to following command:
nssm.exe install ngrok
select the ngrok executable in the window that appears and add the following to the arguments, then press 'Install service'.
start --all --config="C:\path\to\my\config.yml"
The service can now be managed from service manager. To start it open an admin terminal and run the following:
sc start ngrok
Creating a systemd service (Linux - systemd only)
Requires root.
cd into /etc/systemd/system/
Create the following file:
ngrok.service
[Unit]
Description=Ngrok
After=network.service
[Service]
type=simple
User=<your_user_name>
WorkingDirectory=/home/<your_user_name>
ExecStart=/usr/bin/ngrok start --all --config="/path/to/config.yml"
Restart=on-failure
[Install]
WantedBy=multi-user.target
Then run the following command to start and enable the service
systemctl enable ngrok.service && systemctl start ngrok.service
sources:
https://ngrok.com/docs/ngrok-link#service
https://www.freedesktop.org/software/systemd/man/systemd.unit.html
https://nssm.cc/commands
| ngrok | 50,681,671 | 19 |
I have a Vagrant box I'm using for local development. I'm working on a webhook, which is being called from outside; so I'm thinking of using ngrok.com to proxy requests to my Vagrant environment. I'm new to this ngrok thing.
I'm trying to figure out how to access ngrok's web interface, which is normally at http://127.0.0.1:4040. Of course, that doesn't work from my browser, because it's outside of the Vagrant box, so its localhost is not the Vagrant's localhost.
I (think I) have the Vagrant's IP address. I found it in a config.yaml file (yes, with an a), under vm: network: private_network: 192.168.nnn.nnn
Thanks for your help.
| When trying to access a site in a VM, put ngrok in the host machine, and invoke it with:
ngrok http -host-header=rewrite mydomain.com:80
You'll need to access your site (in host machine's browser) with:
http://123456.ngrok.io
But it will rewrite it to mydomain.com.
And you'll be able to access your ngrok dashboard (in host machine's browser) with:
http://127.0.0.1:4040
Docs at https://ngrok.com/docs#host-header. Best of luck!
| ngrok | 33,358,414 | 18 |
I'm creating a rails app that includes devise.
I'm trying to add Twilio messaging to my site with Ngrok, i used this tutorial:
https://www.twilio.com/blog/2016/04/receive-and-reply-to-sms-in-rails.html
I was able to open Ngrok in the console and get the web-id they give for my url.
I keep getting this error when I plug the url into my browser ..I'm supposed to get to my own rails local app. Not sure whats wrong.
What I added in my messaging controller made for ngrok:
class MessagesController < ApplicationController
skip_before_filter :verify_authenticity_token
skip_before_filter :authenticate_user!, :only => "reply"
def reply
message_body = params["Body"]
from_number = params["From"]
boot_twilio
sms = @client.messages.create(
from: Rails.application.secrets.twilio_number,
to: from_number,
body: "Hello there, thanks for texting me. Your number is #{from_number}."
)
#twilio expects a HTTP response to this request
end
private
def boot_twilio
account_sid = Rails.application.secrets.twilio_sid
auth_token = Rails.application.secrets.twilio_token
@client = Twilio::REST::Client.new account_sid, auth_token
end
end
really unsure what is wrong.
when its not connecting to the 'def reply' and authenticate_user should be defined by devise.
| Twilio developer evangelist here.
It looks like this was a problem that Rails 5 seems to have introduced. If the filter hasn't been defined by the time it is used in a controller it will raise an error. This was discovered in the Clearance project too.
Their fix was to pass the raise: false option to skip_before_filter:
class MessagesController < ApplicationController
skip_before_filter :verify_authenticity_token
skip_before_filter :authenticate_user!, :only => "reply", :raise => false
end
| ngrok | 41,266,207 | 18 |
The ASP.NET CORE application, when launched from visual studio, has the address https://localhost:44313/.
To test the performance you need to make a tunnel. I use ngrok and the command:
ngrok http -host-header=localhost 44313
But this does not work for https.
Can anyone share a working example?
|
Download the current version of ngrok
Register and get a token: https://dashboard.ngrok.com/auth
Run ngrok and set the token with the command: ngrok authtoken YOUR_AUTHTOKEN
Create a tunnel:
ngrok http --host-header=localhost https://localhost:44313
Update 11 april 2019
| ngrok | 54,800,512 | 17 |
I'm trying to integrate the Twilio API into my Rails app. The tutorial I found suggested using ngrok to put my app on the internet (rather than working on localhost). I've installed and upnzipped ngrok, and when I try to call it from the directory it is in, I get:
-bash: ngrok: command not found.
Does anyone know what my problem might be? Also could anyone explain what ngrok does vs deploying to heroku? If heroku would work the same, I would just do that. I'm new to using APIs, though, so I'm not clear on why I'm using ngrok.
Thanks!
| If the binary is not located in one of the folders stored in the environment variable $PATH you have to provide at least a relative path to your current location. So if you are in the same folder as the binary then you have to call it with ./ngrok
| ngrok | 26,452,816 | 16 |
I'm used to using a Mac, and ngrok is a breeze; all you need to do is specify a port, but I'm new to IISExpress, and I can't figure out how to use ngrok and/or IIS correctly. To be clear, I've inherited a Windows machine from a coworker (who has left the company) and the set up works great locally.
The local url is similar to:
thing.somedomain.com
In the bindings section of IIS, I've got:
Type Host Name Port IP Address
http thing.somedomain.com 80 *
I've used this page for reference: https://www.twilio.com/blog/2014/03/configure-windows-for-local-webhook-testing-using-ngrok.html
The instructions seem reasonable, but they don't work for me. These instructions indicate that the file applicationhost.config needs to be altered for IIS. I have found this file, and found the correct section for the site I need to ngrok. The binding info does not match what's in the IIS gui though:
<binding protocol="http" bindingInformation="*:4085:localhost" />
As per the instructions, I have added:
<binding protocol="http" bindingInformation="*:4085:whatever.ngrok.io" />
(Here every time I run ngrok on windows I get ngrok.io instead of ngrok.com, which seems odd. I've tried accessing both ways with no luck.)
I have restarted the site on IIS (in the actions menu). When I try to access the ngrok url from a remote machine, ngrok returns 502 bad gateway, and the remote machine shows:
Failed to complete tunnel connection
The connection to http://whatever.ngrok.io was successfully tunneled to your ngrok client, but the client failed to establish a connection to the local address localhost:4085.
Make sure that a web service is running on localhost:4085 and that it is a valid address.
The error encountered was: dial tcp 127.0.0.1:4085: ConnectEx tcp: No connection could be made because the target machine actively refused it.
When I try to go to localhost:4085 locally, I get "This webpage is not available". When I try to go to localhost:80, I get a redirect to a different site the IIS is serving. When I try 127.0.0.1:80, I get a 404 error.
I have tried using netstat -a -b, and have tried all of the ports associated with 127.0.0.1, and nothing turns up the correct site (yet still thing.somedomain.com still works correctly).
I'm completely mystified, and don't know what to try next, or where the problem lies (in how I'm starting ngrok, in how I'm accessing ngrok, in how the bindings are mapped, in how IIS restarts, a firewall issue, or some other voodoo). This should be bloody simple!
| So it turns out that there was nothing to change in the ApplicationHost.config file, AND I was looking at the wrong ApplicationHost.config file (the real file is normally hidden from view in C:/Windows/System32/inetsrv/Config, but you can open it in Notepad from a Command Prompt that has elevated privileges (Run as Administrator)). The actual binding info was:
<binding protocol="http" bindingInformation="*:80:thing.somedomain.com" />
Which is what matched what IIS was showing. That said, what I needed to change was how I invoked ngrok:
ngrok http -host-header=thing.somedomain.com:80
And that was it. I also allowed external traffic to the hostname with this:
netsh http add urlacl url=http://thing.somedomain.com/ user=everyone
| ngrok | 29,972,875 | 15 |
[https://github.com/gtriggiano/ngrok-tunnel ] runs ngrok inside a container. Ngrok is required to run in the container to avert security risks. But am facing problems after running the scripts, which generates the url
$ docker pull gtriggiano/ngrok-tunnel
$ docker run -it -e "TARGET_HOST=localhost" -e "TARGET_PORT=3000" -p 4040 gtriggiano/ngrok-tunnel
am running my rails app on localhost:3000
is it my problem or can it be fixed by altering the scripts(inside the repo)?
| I have started receiving the following error with this now, so this answer may not work for you any more: Your ngrok-agent version "2.3.29" is too old. The minimum supported agent version for your account is "2.3.35". Please update to a newer version with ngrok update, by downloading from https://ngrok.com/download, or by updating your SDK version.
I couldn't get this working but switched to https://github.com/shkoliar/docker-ngrok and it works brilliantly.
In my case I added it to my docker-compose.yml file:
ngrok:
image: shkoliar/ngrok:latest
ports:
- 4551:4551
links:
- web
environment:
- PARAMS=http -region=eu -authtoken=${NGROK_AUTH_TOKEN} localdev.docker:80
networks:
dev_net:
ipv4_address: 10.5.0.10
And it's started with everything else when I do docker-compose up -d
Then there's a web UI at http://localhost:4551/ for you to see the status, requests, the ngrok URLs, etc.
The Github page does have examples of running it manually from the command line too though, rather than via docker-compose:
Command-line Example The example below assumes that you have running
web server docker container named dev_web_1 with exposed port 80.
docker run --rm -it --link dev_web_1 shkoliar/ngrok ngrok http dev_web_1:80
With command line usage, ngrok session is active until it
won't be terminated by Ctrl+C combination.
| ngrok | 53,612,881 | 15 |
I am using the Facebook Messenger Platform to create a generic template. I am currently using ngrok to test locally, and the image_url I input for the generic template never shows in Messenger. The generic template is sent, and the image is just blank. Using Inspect, I can see that the CSS for the image is:
background-image: url("https://external.xx.fbcdn.net/safe_image.php?d=AQA1nM3pKJnllzq0&url=https%3A%2F%2Fdc3858ef.ngrok.io%2Fassets%2Fimages%2Fvideo_image.jpg&_nc_hash=AQAlBOE-vbT8cl-i");
If I open this URL, it is just a black screen with one white pixel in the middle.
Here is the message data that I use:
messageData = {
recipient: {
id: senderID
},
message:{
attachment:{
type: "template",
payload: {
template_type: "generic",
elements: [
{
title:"Test Video Link",
image_url: MY-NGROK_DOMAIN + "/assets/images/video_image.jpg",
subtitle: "Check out this video!",
default_action: {
type: "web_url",
url: "www.google.com"
}
}
]
}
}
}
};
This image_url works fine if I open it in a browser. Similarly, if I create an 'image' type message data rather than 'template', this image is loaded in Messenger.
How can I get my image_url to load properly for a generic template?
| I have the same issue. I and the problem appears when the webhook domain is the same as the image url. If you use an image on a different server, it works.
| ngrok | 46,381,348 | 14 |
I try to work with a webhook to get a JSON,
I read that I should install ngrok because webhooks do not work locally, so I installed ngrok,
and tried to follow this small tuto : https://medium.com/@derek_dyer/rails-webhooks-local-development-7b7c755d85e3
I created my routes :
get 'invoice/webhooks'
post 'invoice/webhooks' =>'invoice#webhooks'
And my controller :
def webhooks
render json: response.body, status: 200
end
I also plugged my URL : https://ce0d99f7.ngrok.io/invoice/webhooks in my service to receive the webhook
I run ./ngrok http 3000 in my terminal and I receive a message
POST /invoice/webhooks 403 Forbidden
Is anyone knows how to fix that ?
| If you using rails 6 and use ngrok in development you must edit the development.rb file in config/environments for add config.hosts << "a0000000.ngrok.io" where a0000000.ngrok.io is the url supplied by ngrok without https:// , if this no work so you must add skip_before_action :verify_authenticity_token in you controller.
| ngrok | 59,412,490 | 12 |
I'm trying to set up an ngrok tunnel to a locally run webserver serving on port 5000. I can access the website fine over localhost:5000, but when I set up an ngrok tunnel on port 5000 I get net::ERR_CONTENT_LENGTH_MISMATCH errors on all of the css and js resources in Chrome 46.0 and Safari 9.0.1.
I do not get these errors when accessing the ngrok link from Firefox 42.
Does anyone know why this is happening, and what I might do to fix it?
| I've resolved this issue just with adding lines bellow in devServer config. So I've changed default express timeout, turned on compression and added proxy. Maybe this will help someone...
keepAliveTimeout: 120000 * 5,
compress: true,
// Set this if you want to enable gzip compression for assets
proxy: {
'**': 'http://localhost:8080'
}
| ngrok | 33,659,218 | 11 |
ngrok's awesome web interface is pointed to http://127.0.0.1:4040 by default. I have other applications listening on that port, however, and need to change it so that ngrok listens on, say, http://127.0.0.1:4045.
| Create a config.yml wherever ngrok is looking for its default config on your platform. If the directory doesn't exist, make it (on windows this is done by entering .ngrok2. as the folder name).
OS X /Users/example/.ngrok2/ngrok.yml
Linux /home/example/.ngrok2/ngrok.yml
Windows C:\Users\example\.ngrok2\ngrok.yml
Then, in config.yml enter
web_addr: 4045
Since this file is in ngrok's default config directory running ngrok http 1337 from the command line, for example, will now run ngrok listening to your server at port 1337 and serving its web interface on http://127.0.0.1:4045
| ngrok | 36,018,375 | 11 |
I have been using ngrok with ASP.NET 4.X without encountering any problems.
Unfortunately, when I try to forward app build in ASP.NET Core 2 I run into a problem that I can't solve.
I tried following combinations of commands to start ngrok:
ngrok http 44374-host-header="localhost:44374"
ngrok http -host-header=rewrite localhost:44374
ngrok http 44374
All give the same result. Ngrok tunnel starts, but when I try to open given forwarding url, site is loading few minutes and then 502 Bad Gateway error is shown. It applies to both http and https version.
Running Visual Studio or ngrok as administrator does not help.
Website works correctly with localhost
Running website with ngrok gives 502 Bad Gateway error
| I solved my problem.
properties/launchSettings.json content:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:59889/",
"sslPort": 44374
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "https://localhost:44374/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"NgrokTEST": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:59890/"
}
}
}
So, it turns out that ASP.NET Core uses different port for SLL connection and it's used by default.
Changing port to normal (59890 in my case) in ngrok solved the problem.
| ngrok | 49,134,294 | 11 |
I'm trying to begin developing a skill for alexa using flask-ask and ngrok in python. Following is my code:
from flask import Flask
from flask_ask import Ask, statement, question, session
import json
import requests
import time
import unidecode
app = Flask(__name__)
ask = Ask(app, "/reddit_reader")
def get_headlines():
titles = 'is this working'
return titles
@app.route('/')
def homepage():
return "hi there, how ya doin?"
@ask.launch
def start_skill():
welcome_message = 'Hello there, would you like the news?'
return question(welcome_message)
@ask.intent("YesIntent")
def share_headlines():
headlines = get_headlines()
headline_msg = 'The current world news headlines are
{}'.format(headlines)
return statement(headline_msg)
@ask.intent("NoIntent")
def no_intent():
bye_text = 'I am not sure why you asked me to run then, but okay... bye'
return statement(bye_text)
if __name__ == '__main__':
app.run(debug=True)
The code runs fine on my machine and returns the correct output if I print it out. But the skill gives a HTTP 500 internal error when I deploy it on amazon using ngrok. I get the same 500 internal error both in the text as well as json simulator in the development console.
This is my intent schema:
{
"intents": [
{
"intent": "YesIntent"
},
{
"intent": "NoIntent"
}
]
}
I get the following error in my python prompt:
AttributeError: module 'lib' has no attribute 'X509V3_EXT_get
The stacktrace is as follows:
Traceback (most recent call last):
File "C:\Python36\lib\site-packages\flask\app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python36\lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "C:\Python36\lib\site-packages\flask\app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python36\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python36\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python36\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python36\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python36\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python36\lib\site-packages\flask_ask\core.py", line 728, in _flask_view_func
ask_payload = self._alexa_request(verify=self.ask_verify_requests)
File "C:\Python36\lib\site-packages\flask_ask\core.py", line 662, in _alexa_request
cert = verifier.load_certificate(cert_url)
File "C:\Python36\lib\site-packages\flask_ask\verifier.py", line 21, in load_certificate
if not _valid_certificate(cert):
File "C:\Python36\lib\site-packages\flask_ask\verifier.py", line 63, in _valid_certificate
value = str(extension)
File "C:\Python36\lib\site-packages\OpenSSL\crypto.py", line 779, in __str__
return self._subjectAltNameString()
File "C:\Python36\lib\site-packages\OpenSSL\crypto.py", line 740, in _subjectAltNameString
method = _lib.X509V3_EXT_get(self._extension)
AttributeError: module 'lib' has no attribute 'X509V3_EXT_get'
Pip freeze output:
aniso8601==1.2.0
asn1crypto==0.24.0
certifi==2018.1.18
cffi==1.11.5
chardet==3.0.4
click==6.7
cryptography==2.2
Flask==0.12.1
Flask-Ask==0.9.8
idna==2.6
itsdangerous==0.24
Jinja2==2.10
MarkupSafe==1.0
pycparser==2.18
pyOpenSSL==17.0.0
python-dateutil==2.7.0
PyYAML==3.12
requests==2.18.4
six==1.11.0
Unidecode==1.0.22
urllib3==1.22
Werkzeug==0.14.1
I've tried running it on both python 2.7 and python 3.6. Any help is appreciated
| Ran into the same issue, you can fix it by downgrading cryptography to anything less than 2.2 for me.
pip install 'cryptography<2.2'
rpg711 gets all the credit (see comments the on original post)
| ngrok | 49,375,054 | 11 |
I have a MongoDb hosted locally in my machine and runs successfully in port localhost:27017. The database has a user name and password with a collection named, "testDb". In the code, I am able to access the database successfully using localhost.
I am trying to access this MongoDb from a remote desktop using ngrok. I hace implemented the port forwarding and the following response is shown in the command prompt.
Forwarding https://5e825c82.ngrok.io -> http://localhost:27017
I also tried changing the port =>
Forwarding https://5e825c82.ngrok.io -> http://localhost:28017
Both ports failed with the following Error message:
The connection to http://5e825c82.ngrok.io was successfully tunneled to your ngrok client, but the client failed to establish a connection to the local address localhost:28017.
Make sure that a web service is running on localhost:28017 and that it is a valid address.
The error encountered was: dial tcp [::1]:28017: connectex: No connection could be made because the target machine actively refused it.
// Works fine
MongoClient client = new MongoClient("mongodb://admin:admin@localhost:27017/testDb");
// Fails:
MongoClient client = new MongoClient("mongodb://admin:[email protected]/testDb");
I would like to know how to establish a connection to the MongoDb with ngrok.
| MongoDB uses TCP not HTTP.
Try following command :
ngrok tcp 27017
(note the tcp, not http which I think is what you used)
There are a couple of extra steps you need to do for some reason when you use TCP, and ngrok will prompt you and tell you what you need to do when you try the above command.
Sign up for an ngrok account at https://dashboard.ngrok.com/get-started
Run locally the command shown on this page in the box 3. Connect your account (eg. ngrok authtoken 123ABC456ETC)
Now try that command again (ngrok tcp 27017)
| ngrok | 57,220,540 | 10 |
I'm using Docker I have implemented a system to deploy environments (on a single server) based on Git branches using Traefik (*.dev.domain.com) and Docker Compose templates.
I like Kubernetes and I've never switched to it since I'm limited to one single server for my infrastructure. I've only used it using local installations (Docker for Windows).
So, my question is: does it make sense to run a Kubernetes "cluster" (master and nodes) on a single server to orchestrate and route containers (in place of Traefik/Rancher/Docker Compose)?
This use is for development and staging only for the moment, so high availability is not a prerequisite.
| AFAIU,
I do not see a requirement for kubernetes unless we are doing below at least for single host using native docker run or docker-compose or docker engine swarm mode -
Make sure there are enough(>=2) replicas of your app in a single server and you are balancing the load across those apps docker containers.
If you want to go bit advanced, we should be able to scale up & down dynamically (docker swarm mode supports this out of the box else use jwilder nginx proxy).
Your deployment should not cause a downtime. Make sure a single container is always healthy at any instant of time while deploying.
Container should auto heal(restart automatically) in case your HTTP or TCP health check fails.
Doing all of the above will certainly put you in a better place but single host is still a single source of failure which you got to deal with at regular intervals.
Preferred : if possible try to start with docker engine swarm mode or kubernetes single master or minikube. This will automatically take care of all the above scenarios out of the box and will also allow you to further scale up anytime by adding more nodes without changing much in your YML files for docker swarm or kubernetes.
Ref -
https://kubernetes.io/docs/setup/independent/create-cluster-kubeadm/
https://docs.docker.com/engine/swarm/
| Traefik | 52,800,958 | 28 |
I meet some problems using traefik with docker and I don't know why.
With some containers, it's works like a charm and for other ones, I have an error when I try to access to these ones : Bad gateway (error 502).
Here is my traefik.toml :
# Service logs (here debug mode)
debug = true
logLevel = "DEBUG"
defaultEntryPoints = ["http", "https"]
# Access log
filePath = "/var/log/traefik/access.log"
format = "common"
################################################################
# Web configuration backend
################################################################
[web]
address = ":8080"
################################################################
# Entry-points configuration
################################################################
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
################################################################
# Docker configuration backend
################################################################
[docker]
domain = "domain.tld"
watch = true
exposedbydefault = false
endpoint = "unix:///var/run/docker.sock"
################################################################
# Let's encrypt
################################################################
[acme]
email = "[email protected]"
storageFile = "acme.json"
onDemand = false
onHostRule = true
entryPoint = "https"
[acme.httpChallenge]
entryPoint = "http"
[[acme.domains]]
main = "domain.tld"
sans = ["docker.domain.tld", "traefik.domain.tld", "phpmyadmin.domain.tld", "perso.domain.tld", "muximux.domain.tld", "wekan.domain.tld", "wiki.domain.tld", "cloud.domain.tld", "email.domain.tld"]
Here is my docker-compose.yml (for portainer, which is a container which works) :
version: '2'
services:
portainer:
restart: always
image: portainer/portainer:latest
container_name: "portainer"
#Automatically choose 'Manage the Docker instance where Portainer is running' by adding <--host=unix:///var/run/docker.sock> to the command
ports:
- "9000:9000"
networks:
- traefik-network
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ../portainer:/data
labels:
- traefik.enable=true
- traefik.backend=portainer
- traefik.frontend.rule=Host:docker.domain.tld
- traefik.docker.network=traefik-network
- traefik.port=9000
- traefik.default.protocol=http
networks:
traefik-network:
external : true
If I go to docker.domain.tld, it works ! and in https, with valide let's encrypt certificate :)
Here is my docker-compose.yml (for dokuwiki, which is a container which does not work) :
version: '2'
services:
dokuwiki:
container_name: "dokuwiki"
image: bitnami/dokuwiki:latest
restart: always
volumes:
- ../dokuwiki/data:/bitnami
ports:
- "8085:80"
- "7443:443"
networks:
- traefik-network
labels:
- traefik.backend=dokuwiki
- traefik.docker.network=traefik-network
- traefik.frontend.rule=Host:wiki.domain.tld
- traefik.enable=true
- traefik.port=8085
- traefik.default.protocol=http
networks:
traefik-network:
external: true
If I go to wiki.domain.tld, it does not work ! I have a bad gateway error on the browser. I have tried to change the traefik.port to 7443 and the traefik.default.protocol to https but I have the same error. Of course it works when I try to access the wiki with the IP and the port (in http / https). I have bad gateway only when I type wiki.domain.tld.
So, I don't understand why it works for some containers and not for other ones with the same declaration.
| The traefik port should be the http port of the container, not the published port on the host. It communicates over the docker network, so publishing the port is unnecessary and against the goals of only having a single port published with a reverse proxy to access all the containers.
In short, you need:
traefik.port=80
Since this question has gotten lots of views, the other reason lots of people see a 502 from traefik is placing the containers on a different docker network from the traefik instance, or having a container on multiple networks and not telling traefik which network to use. This doesn't apply in your case since you have the following lines in your compose file that match up with the traefik service's network:
services:
dokuwiki:
networks:
- traefik-network
labels:
- traefik.docker.network=traefik-network
networks:
traefik-network:
external : true
Even if you only assign a service to a single network, some actions like publishing a port will result in your service being attached to two different networks (the ingress network being the second). The network name in the label needs to be the external name, which in your case is the same, but for others that do not specify their network as external, it may have a project or stack name prefixed which you can see in the docker network ls output.
| Traefik | 49,417,889 | 27 |
First of all I'm sorry if I'm not using the right terms to ask this question, but I'm not up to the terminology in place.
I have traefik running in a docker container and serving some services with the PathPrefix option, for instance, www.myserver.com/wordpress redirects to a docker container running wordpress.
But how do I get it to redirect to outside a docker container? Specifically, how do I get www.myserver.com to redirect to port 8080 in my machine to serve a service I have running there in the host OS (not in a docker container)?
This is my traefik.toml:
logLevel = "DEBUG"
defaultEntryPoints = ["http", "https"]
[entryPoints]
[entryPoints.http]
address = ":80"
compress = false
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
[acme]
email = "[email protected]"
storage = "acme.json"
entryPoint = "https"
onHostRule = true
#onDemand = true
[[acme.domains]]
main = "www.myserver.com"
[web]
address = ":8888"
[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "www.myserver.com"
watch = true
exposedbydefault = false
And my docker-compose.yml for the traefik container:
version: "2"
services:
traefik:
image: traefik
network_mode: "host"
ports:
- "80:80"
- "443:443"
- "8888:8888"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ${SERVER_DIR}/AppData/traefik:/etc/traefik/
- ${PWD}/acme.json:/acme.json
- ${PWD}/traefik.toml:/etc/traefik/traefik.toml
- ${PWD}/servers.toml:/etc/traefik/servers.toml
restart: never
| With the new Traefik (v.2) you need to use a combination of labels and an external file, you can find below my working example.
In your docker compose you need to add the comands to define the external file and enable the provider
- "--providers.file=true"
- "--providers.file.filename=/etc/traefik/rules.toml"
Into your file (rules.toml) the routing to foward to your external service (be aware of the syntax, use the char to define the host ( ` ) )
example :
Docker-compose:
traefik:
image: "traefik:v2.0.0"
container_name: "traefik"
restart: always
command:
- "--api.insecure=true"
- "--providers.docker=true"
- "--providers.docker.exposedbydefault=false"
- "--entrypoints.web.address=:80"
- "--entrypoints.websecure.address=:443"
- "--certificatesresolvers.myhttpchallenge.acme.httpchallenge=true"
- "--certificatesresolvers.myhttpchallenge.acme.httpchallenge.entrypoint=web"
- "[email protected]"
- "--providers.file=true"
- "--providers.file.filename=/etc/traefik/rules.toml"
- "--providers.docker=true"
- "--providers.file.watch=true"
ports:
- "80:80"
- "8080:8080"
- "443:443"
networks:
- proxy
environment:
- CF_API_EMAIL="xx"
- CF_API_KEY="xx"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:ro"
- "./traefik/rules.toml:/etc/traefik/rules.toml"
Rules.toml
[http.routers]
# Define a connection between requests and services
[http.routers.nasweb]
rule = "Host(`nas.xxxx.com`)"
entrypoints = ["websecure"]
service = "nas"
[http.routers.nasweb.tls]
certResolver = "myhttpchallenge"
[http.services]
# Define how to reach an existing service on our infrastructure
[http.services.nas.loadBalancer]
[[http.services.nas.loadBalancer.servers]]
url = "http://192.168.0.165:80"
| Traefik | 46,245,684 | 26 |
I'd like to serve static ressources such as images, js bundles, html pages... with Traefik like I was able to do with nginx
# nginx config
server {
root /www/data;
location ~ \.js {
root /www/bundles;
}
}
Many thanks
Cheers
| Traefik doesn't serve static files (it's a not a web server it's a reverse proxy/load balancer).
You must use a container, which contains a web server with your files.
| Traefik | 46,503,797 | 23 |
I have a problem with setting up mailcow with traefik, I encounter gateway timeouts. I also have this problem with nextcloud, so I would be really interested, what causes these issues with gateway timeout.
I guess it has to do with port 9000 and php-fpm upstream or sth.
But I want to know for sure, and how to deal with it.
My traefik.toml:
debug = true
checkNewVersion = true
defaultEntryPoints = ["http", "https"]
[web]
address = ":8080"
[web.auth.basic]
users = ["admin:undecipherablestring"]
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
[acme]
email = "[email protected]"
storage = "acme.json"
entryPoint = "https"
onHostRule = true
[[acme.domains]]
main = "main.com"
sans = ["monitor.main.com", "ports.main.com", "git.main.com", "cloud.main.com", "mail.main.com"]
My traefik docker-compose.yml:
version: '2'
services:
proxy:
image: traefik
container_name: traefik
restart: always
command: |-
--docker
--docker.domain=docker.localhost
--logLevel=DEBUG
networks:
- webgateway
labels:
- "traefik.frontend.rule=Host: monitor.main.com"
- "traefik.port=8080"
ports:
- "80:80"
- "443:443"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./traefik.toml:/traefik.toml
- ./acme.json:/acme.json
- acme:/opt/traefik/acme
networks:
webgateway:
driver: bridge
volumes:
acme:
driver: local
My mailcow docker-compose.yml:
version: '2.1'
services:
unbound-mailcow:
image: mailcow/unbound:1.0
build: ./data/Dockerfiles/unbound
command: /usr/sbin/unbound
depends_on:
mysql-mailcow:
condition: service_healthy
healthcheck:
test: ["CMD", "nslookup", "google.com", "127.0.0.1"]
interval: 30s
timeout: 3s
retries: 10
volumes:
- ./data/conf/unbound/unbound.conf:/etc/unbound/unbound.conf:ro
restart: always
networks:
mailcow-network:
ipv4_address: 172.22.1.254
aliases:
- unbound
mysql-mailcow:
image: mariadb:10.1
command: mysqld --max_allowed_packet=128M
healthcheck:
test: ["CMD", "mysqladmin", "ping", "--host", "localhost", "--silent"]
interval: 5s
timeout: 5s
retries: 10
volumes:
- mysql-vol-1:/var/lib/mysql/
- ./data/conf/mysql/:/etc/mysql/conf.d/:ro
environment:
- MYSQL_ROOT_PASSWORD=${DBROOT}
- MYSQL_DATABASE=${DBNAME}
- MYSQL_USER=${DBUSER}
- MYSQL_PASSWORD=${DBPASS}
restart: always
dns:
- 172.22.1.254
dns_search: mailcow-network
networks:
mailcow-network:
ipv4_address: 172.22.1.250
aliases:
- mysql
redis-mailcow:
image: redis:alpine
depends_on:
unbound-mailcow:
condition: service_healthy
volumes:
- redis-vol-1:/data/
restart: always
dns:
- 172.22.1.254
dns_search: mailcow-network
networks:
mailcow-network:
ipv4_address: 172.22.1.249
aliases:
- redis
clamd-mailcow:
image: mailcow/clamd:1.1
build: ./data/Dockerfiles/clamd
restart: always
environment:
- SKIP_CLAMD=${SKIP_CLAMD:-n}
dns:
- 172.22.1.254
dns_search: mailcow-network
networks:
mailcow-network:
aliases:
- clamd
rspamd-mailcow:
image: mailcow/rspamd:1.3
build: ./data/Dockerfiles/rspamd
command: >
/bin/bash -c "
sleep 5;
/usr/bin/rspamd -f -u _rspamd -g _rspamd
"
depends_on:
- nginx-mailcow
volumes:
- ./data/conf/rspamd/override.d/:/etc/rspamd/override.d:ro
- ./data/conf/rspamd/local.d/:/etc/rspamd/local.d:ro
- ./data/conf/rspamd/lua/:/etc/rspamd/lua/:ro
- dkim-vol-1:/data/dkim
- rspamd-vol-1:/var/lib/rspamd
restart: always
dns:
- 172.22.1.254
dns_search: mailcow-network
hostname: rspamd
networks:
mailcow-network:
ipv4_address: 172.22.1.253
aliases:
- rspamd
php-fpm-mailcow:
image: mailcow/phpfpm:1.0
build: ./data/Dockerfiles/phpfpm
command: "php-fpm -d date.timezone=${TZ}"
depends_on:
- redis-mailcow
volumes:
- ./data/web:/web:ro
- ./data/conf/rspamd/dynmaps:/dynmaps:ro
- dkim-vol-1:/data/dkim
environment:
- DBNAME=${DBNAME}
- DBUSER=${DBUSER}
- DBPASS=${DBPASS}
- MAILCOW_HOSTNAME=${MAILCOW_HOSTNAME}
- IMAP_PORT=${IMAP_PORT:-143}
- IMAPS_PORT=${IMAPS_PORT:-993}
- POP_PORT=${POP_PORT:-110}
- POPS_PORT=${POPS_PORT:-995}
- SIEVE_PORT=${SIEVE_PORT:-4190}
- SUBMISSION_PORT=${SUBMISSION_PORT:-587}
- SMTPS_PORT=${SMTPS_PORT:-465}
- SMTP_PORT=${SMTP_PORT:-25}
restart: always
dns:
- 172.22.1.254
dns_search: mailcow-network
networks:
mailcow-network:
aliases:
- phpfpm
sogo-mailcow:
image: mailcow/sogo:1.3
build: ./data/Dockerfiles/sogo
depends_on:
unbound-mailcow:
condition: service_healthy
environment:
- DBNAME=${DBNAME}
- DBUSER=${DBUSER}
- DBPASS=${DBPASS}
- TZ=${TZ}
- MAILCOW_HOSTNAME=${MAILCOW_HOSTNAME}
volumes:
- ./data/conf/sogo/:/etc/sogo/
restart: always
dns:
- 172.22.1.254
dns_search: mailcow-network
networks:
mailcow-network:
ipv4_address: 172.22.1.252
aliases:
- sogo
dovecot-mailcow:
image: mailcow/dovecot:1.4
build: ./data/Dockerfiles/dovecot
depends_on:
unbound-mailcow:
condition: service_healthy
volumes:
- ./data/conf/dovecot:/usr/local/etc/dovecot
- ./data/assets/ssl:/etc/ssl/mail/:ro
- ./data/conf/sogo/:/etc/sogo/
- vmail-vol-1:/var/vmail
- crypt-vol-1:/mail_crypt/
environment:
- DBNAME=${DBNAME}
- DBUSER=${DBUSER}
- DBPASS=${DBPASS}
ports:
- "${DOVEADM_PORT:-127.0.0.1:19991}:12345"
- "${IMAP_PORT:-143}:143"
- "${IMAPS_PORT:-993}:993"
- "${POP_PORT:-110}:110"
- "${POPS_PORT:-995}:995"
- "${SIEVE_PORT:-4190}:4190"
restart: always
dns:
- 172.22.1.254
dns_search: mailcow-network
hostname: ${MAILCOW_HOSTNAME}
networks:
mailcow-network:
aliases:
- dovecot
postfix-mailcow:
image: mailcow/postfix:1.2
build: ./data/Dockerfiles/postfix
depends_on:
unbound-mailcow:
condition: service_healthy
volumes:
- ./data/conf/postfix:/opt/postfix/conf
- ./data/assets/ssl:/etc/ssl/mail/:ro
- postfix-vol-1:/var/spool/postfix
- crypt-vol-1:/var/lib/zeyple
environment:
- DBNAME=${DBNAME}
- DBUSER=${DBUSER}
- DBPASS=${DBPASS}
ports:
- "${SMTP_PORT:-25}:25"
- "${SMTPS_PORT:-465}:465"
- "${SUBMISSION_PORT:-587}:587"
restart: always
dns:
- 172.22.1.254
dns_search: mailcow-network
hostname: ${MAILCOW_HOSTNAME}
networks:
mailcow-network:
aliases:
- postfix
memcached-mailcow:
image: memcached:alpine
depends_on:
unbound-mailcow:
condition: service_healthy
restart: always
dns:
- 172.22.1.254
dns_search: mailcow-network
networks:
mailcow-network:
aliases:
- memcached
nginx-mailcow:
depends_on:
- sogo-mailcow
- php-fpm-mailcow
image: nginx:mainline-alpine
healthcheck:
test: ["CMD", "ping", "php-fpm-mailcow", "-c", "5"]
interval: 5s
timeout: 5s
retries: 10
command: /bin/sh -c "envsubst < /etc/nginx/conf.d/templates/listen_plain.template > /etc/nginx/conf.d/listen_plain.active &&
envsubst < /etc/nginx/conf.d/templates/listen_ssl.template > /etc/nginx/conf.d/listen_ssl.active &&
envsubst < /etc/nginx/conf.d/templates/server_name.template > /etc/nginx/conf.d/server_name.active &&
nginx -g 'daemon off;'"
environment:
- HTTPS_PORT=${HTTPS_PORT:-443}
- HTTP_PORT=${HTTP_PORT:-80}
- MAILCOW_HOSTNAME=${MAILCOW_HOSTNAME}
volumes:
- ./data/web:/web:ro
- ./data/conf/rspamd/dynmaps:/dynmaps:ro
- ./data/assets/ssl/:/etc/ssl/mail/:ro
- ./data/conf/nginx/:/etc/nginx/conf.d/:rw
expose:
- "${HTTP_PORT:-80}"
#ports:
#- "${HTTPS_BIND:-0.0.0.0}:${HTTPS_PORT:-443}:${HTTPS_PORT:-443}"
#- "${HTTP_BIND:-0.0.0.0}:${HTTP_PORT:-80}:${HTTP_PORT:-80}"
restart: always
dns:
- 172.622.1.254
dns_search: mailcow-network
labels:
- "traefik.frontend.rule=Host: ${MAILCOW_HOSTNAME}"
- "traefik.backend=mailcow"
- "traefik.port=80"
- "traefik.frontend.entryPoints=http,https"
- "traefik.docker.network=traefik"
networks:
mailcow-network:
ipv4_address: 172.22.1.251
aliases:
- nginx
traefik:
acme-mailcow:
depends_on:
- nginx-mailcow
image: mailcow/acme:1.12
build: ./data/Dockerfiles/acme
dns:
- 172.22.1.254
dns_search: mailcow-network
environment:
- ADDITIONAL_SAN=${ADDITIONAL_SAN}
- MAILCOW_HOSTNAME=${MAILCOW_HOSTNAME}
- DBNAME=${DBNAME}
- DBUSER=${DBUSER}
- DBPASS=${DBPASS}
- SKIP_LETS_ENCRYPT=${SKIP_LETS_ENCRYPT:-n}
- SKIP_IP_CHECK=${SKIP_IP_CHECK:-n}
volumes:
- ./data/web/.well-known/acme-challenge:/var/www/acme:rw
- ./data/assets/ssl:/var/lib/acme/:rw
- ./data/assets/ssl-example:/var/lib/ssl-example/:ro
- /var/run/docker.sock:/var/run/docker.sock:ro
# do not restart the container too often. Things get worse when we hit let's encrypt's ratelimit.
restart: on-failure:1
networks:
mailcow-network:
aliases:
- acme
fail2ban-mailcow:
image: mailcow/fail2ban:1.5
build: ./data/Dockerfiles/fail2ban
depends_on:
- dovecot-mailcow
- postfix-mailcow
- sogo-mailcow
- php-fpm-mailcow
- redis-mailcow
restart: always
privileged: true
environment:
- TZ=${TZ}
- SKIP_FAIL2BAN=${SKIP_FAIL2BAN:-no}
network_mode: "host"
dns:
- 172.22.1.254
dns_search: mailcow-network
volumes:
- /lib/modules:/lib/modules:ro
ipv6nat:
image: robbertkl/ipv6nat
restart: always
privileged: true
network_mode: "host"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- /lib/modules:/lib/modules:ro
networks:
mailcow-network:
driver: bridge
enable_ipv6: true
ipam:
driver: default
config:
- subnet: 172.22.1.0/24
- subnet: fd4d:6169:6c63:6f77::/64
traefik:
external:
name: traefik_webgateway
volumes:
vmail-vol-1:
mysql-vol-1:
dkim-vol-1:
redis-vol-1:
rspamd-vol-1:
postfix-vol-1:
crypt-vol-1:
| I think I may have had a similar issue to what you are/were experiencing. Take a look at this GitHub issue: https://github.com/containous/traefik/issues/979
If your problem is the same as mine, here is the issue:
Traefik is on a "front facing" network, so is one of your services, but that service is also part of a "back facing" network. Traefik, by default, doesn't know what network to send requests to... so it sends them to a randomly chosen one of the two IP address options (picked at the creation of that container). If Traefik isn't part of that network, it wont be able to reach that container, and will give you a Gateway Timeout.
Solution: add a label to your container to directly specify to Traefik what network it should be communicating on:
labels:
- "traefik.enable=true"
- "traefik.docker.network=<folder prefix>webgateway"
- "traefik.backend=<backend service"
- "traefik.frontend.rule=Host:<host setting>"
Pro tip: use docker network ls to figure out what the actual name of your network is, because it is not what docker-compose says in the file. The actual network name is prefixed based on the name of the folder that it is run in. (I don't know why, and I don't like it, but that is the world we live in)
Hence the <folder prefix> in my above example.
| Traefik | 46,161,017 | 21 |
I'm currently trying to get traefik to use multiple routers and services on a single container, which isn't working and i don't know if this is intended at all.
Why?
Specificly i'm using an gitlab omnibus container and wanted to use / access multiple services inside the omnibus container since gitlab is providing not only "the gitlab website" with it.
What did i try?
I simply tried adding another router to my docker compose file via labels
This is what i have:
labels:
- "traefik.http.routers.gitlab.rule=Host(`gitlab.example.com`)"
- "traefik.http.services.gitlab.loadbalancer.server.port=80"
This is what i want:
labels:
- "traefik.http.routers.gitlab.rule=Host(`gitlab.example.com`)"
- "traefik.http.services.gitlab.loadbalancer.server.port=80"
- "traefik.http.routers.registry.rule=Host(`registry.gitlab.example.com`)"
- "traefik.http.services.registry.loadbalancer.server.port=5000"
This doesn't work since traefik probably getting confused with what to route to which service and i couldn't find a mechanism that tells traefik exactly which router goes to which service in a case like this.
Is this even possible or am i just missing a little bit of traefik magic?
| I found the solution to my Question.
There's indeed a little bit i missed:
traefik.http.routers.myRouter.service=myService
With this Label i can point a Router to a specific Service and should be able to add multiple services to one container:
labels:
- "traefik.http.routers.gitlab.rule=Host(`gitlab.example.com`)"
- "traefik.http.routers.gitlab.service=gitlab"
- "traefik.http.services.gitlab.loadbalancer.server.port=80"
- "traefik.http.routers.registry.rule=Host(`registry.gitlab.example.com`)"
- "traefik.http.routers.registry.service=registry"
- "traefik.http.services.registry.loadbalancer.server.port=5000"
Here each router is pointed to a specific service explicitly which normally happens implicitly.
| Traefik | 59,856,722 | 21 |
I've got some strange issue. I have following setup:
one docker-host running traefik as LB serving multiple sites. sites are most php/apache. HTTPS is managed by traefik.
Each site is started using a docker-compose YAML containing the following:
version: '2.3'
services:
redis:
image: redis:alpine
container_name: ${PROJECT}-redis
networks:
- internal
php:
image: registry.gitlab.com/OUR_NAMESPACE/docker/php:${PHP_IMAGE_TAG}
environment:
- APACHE_DOCUMENT_ROOT=${APACHE_DOCUMENT_ROOT}
container_name: ${PROJECT}-php-fpm
volumes:
- ${PROJECT_PATH}:/var/www/html:cached
- .docker/php/php-ini-overrides.ini:/usr/local/etc/php/conf.d/99-overrides.ini
ports:
- 80
networks:
- proxy
- internal
labels:
- traefik.enable=true
- traefik.port=80
- traefik.frontend.headers.SSLRedirect=false
- traefik.frontend.rule=Host:${PROJECT}
- "traefik.docker.network=proxy"
networks:
proxy:
external:
name: proxy
internal:
(as PHP we use 5.6.33-apache-jessie or 7.1.12-apache f.e.)
Additionally to above, some sites get following labels:
traefik.docker.network=proxy
traefik.enable=true
traefik.frontend.headers.SSLRedirect=true
traefik.frontend.rule=Host:example.com, www.example.com
traefik.port=80
traefik.protocol=http
what we get is that some requests end in 502 Bad Gateway
traefik debug output shows:
time="2018-03-21T12:20:21Z" level=debug msg="vulcand/oxy/forward/http: Round trip: http://172.18.0.8:80, code: 502, Length: 11, duration: 2.516057159s"
can someone help with that?
it's completely random when it happens
our traefik.toml:
debug = true
checkNewVersion = true
logLevel = "DEBUG"
defaultEntryPoints = ["https", "http"]
[accessLog]
[web]
address = ":8080"
[web.auth.digest]
users = ["admin:traefik:some-encoded-pass"]
[entryPoints]
[entryPoints.http]
address = ":80"
# [entryPoints.http.redirect] # had to disable this because HTTPS must be enable manually (not my decission)
# entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
[retry]
[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "example.com"
watch = true
exposedbydefault = false
[acme]
email = "[email protected]"
storage = "acme.json"
entryPoint = "https"
onHostRule = true
[acme.httpChallenge]
entryPoint = "http"
Could the issue be related to using the same docker-compose.yml?
| Another reason can be that you might be accidentally mapping to the vm's port instead of the container port.
I made a change to my port mapping on the docker-compose file and forgot to update the labeled port so it was trying to map to a port on the machine that was not having any process attached to it
Wrong way:
ports:
- "8080:8081"
labels:
- "traefik.http.services.front-web.loadbalancer.server.port=8080"
Right way
ports:
- "8080:8081"
labels:
- "traefik.http.services.front-web.loadbalancer.server.port=8081"
Also in general don't do this, instead of exposing ports try docker networks they are much better and cleaner. I made my configuration documentation like a year ago and this was more of a beginner mistake on my side but might help someone :)
| Traefik | 49,406,737 | 18 |
I cannot figure out how to get a simple service to be accessible by both http and https on localhost. This is my setup so far and I'm using traefik V2.xxx.
I want to be able to hit this site using both https/http protocols (for reasons on dev machines only). The https works just fine but http does NOT. What labels do I need to add/remove/change?
http://whoami.localhost:8000/
https://whoami.localhost:8443/
docker-compose.yml
version: "3.7"
services:
whoami:
image: containous/whoami
labels:
- traefik.enable=true
- traefik.http.routers.whoami.rule=Host(`whoami.localhost`)
- traefik.http.routers.whoami.entrypoints=web,web-secure
- traefik.http.routers.whoami.tls=true
- traefik.protocol=http,https
reverse-proxy:
depends_on:
- whoami
image: traefik:v2.1.1
ports:
- 8000:80
- 8443:443
- 8001:8080
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./traefik:/etc/traefik:ro
traefik/traefik.toml
[log]
level = "DEBUG"
[accessLog]
filePath = "/logs/access.log"
bufferingSize = 20
[docker]
exposedbydefault = false
[api]
dashboard = true
insecure = true
[providers]
[providers.file]
filename = "/etc/traefik/traefik.toml"
watch = true
[providers.docker]
exposedbydefault = false
[[tls.certificates]]
certFile = "/etc/traefik/certs/localhost-cert.pem"
keyFile = "/etc/traefik/certs/localhost-key.pem"
[entryPoints]
[entryPoints.web]
address = ":80"
[entryPoints.web-secure]
address = ":443"
C:\Windows\System32\drivers\etc\hosts
127.0.0.1 whoami.localhost
| Finally got this working. The traefik docs are squarely in the esoteric region on certain topics and given the recent major 2.0 release there isn't a lot of examples out there yet.
Here is my working docker-compose.yml file where the application is now being exposed using the same host "whomai.localhost" and on both port 8000 (http) and 8443 (https).
version: "3.7"
services:
whoami:
image: containous/whoami
labels:
- traefik.enable=true
- traefik.http.routers.whoami-http.rule=Host(`whoami.localhost`)
- traefik.http.routers.whoami-http.entrypoints=web
- traefik.http.routers.whoami-http.service=whoami-http-service
- traefik.http.services.whoami-http-service.loadbalancer.server.port=80
- traefik.http.routers.whoami-https.rule=Host(`whoami.localhost`)
- traefik.http.routers.whoami-https.entrypoints=web-secure
- traefik.http.routers.whoami-https.service=whoami-https-service
- traefik.http.services.whoami-https-service.loadbalancer.server.port=80
- traefik.http.routers.whoami-https.tls=true
reverse-proxy:
depends_on:
- whoami
image: traefik:v2.1.1
ports:
- 8000:80
- 8443:443
- 8001:8080
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./traefik:/etc/traefik:ro
Routers and services in trafik 2.x can be dynamically created using whatever naming convention you want using docker labels. In this setup I just called them whoami-http and whoami-https for the routers and whoami-http-service and whoami-https-service for the services. Since I am dynamically creating my own routers/services instead of using the defaults the load-balancer for each service must be explicitly told the server port for the targeted application. Since the whoami app only exposes port 80 itself and TLS is terminated at traefik this is defined as port 80 for both http and https services.
All of the labels shown above are required and cannot be omitted for this type of custom router/service setup.
I'm using mkcert on Windows 10 for valid local certificates in case you were wondering.
mkcert -install
mkcert -key-file traefik\certs\localhost-key.pem -cert-file traefik\certs\localhost-cert.pem whoami.localhost localhost 127.0.0.1 ::1
| Traefik | 59,830,648 | 18 |
Motivations
I am a running into an issue when trying to proxy PostgreSQL with Traefik over SSL using Let's Encrypt.
I did some research but it is not well documented and I would like to confirm my observations and leave a record to everyone who faces this situation.
Configuration
I use latest versions of PostgreSQL v12 and Traefik v2. I want to build a pure TCP flow from tcp://example.com:5432 -> tcp://postgresql:5432 over TLS using Let's Encrypt.
Traefik service is configured as follow:
version: "3.6"
services:
traefik:
image: traefik:latest
restart: unless-stopped
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:ro"
- "./configuration/traefik.toml:/etc/traefik/traefik.toml:ro"
- "./configuration/dynamic_conf.toml:/etc/traefik/dynamic_conf.toml"
- "./letsencrypt/acme.json:/acme.json"
networks:
- backend
ports:
- "80:80"
- "443:443"
- "5432:5432"
networks:
backend:
external: true
With the static setup:
[entryPoints]
[entryPoints.web]
address = ":80"
[entryPoints.web.http]
[entryPoints.web.http.redirections.entryPoint]
to = "websecure"
scheme = "https"
[entryPoints.websecure]
address = ":443"
[entryPoints.websecure.http]
[entryPoints.websecure.http.tls]
certresolver = "lets"
[entryPoints.postgres]
address = ":5432"
PostgreSQL service is configured as follow:
version: "3.6"
services:
postgresql:
image: postgres:latest
environment:
- POSTGRES_PASSWORD=secret
volumes:
- ./configuration/trial_config.conf:/etc/postgresql/postgresql.conf:ro
- ./configuration/trial_hba.conf:/etc/postgresql/pg_hba.conf:ro
- ./configuration/initdb:/docker-entrypoint-initdb.d
- postgresql-data:/var/lib/postgresql/data
networks:
- backend
#ports:
# - 5432:5432
labels:
- "traefik.enable=true"
- "traefik.docker.network=backend"
- "traefik.tcp.routers.postgres.entrypoints=postgres"
- "traefik.tcp.routers.postgres.rule=HostSNI(`example.com`)"
- "traefic.tcp.routers.postgres.tls=true"
- "traefik.tcp.routers.postgres.tls.certresolver=lets"
- "traefik.tcp.services.postgres.loadBalancer.server.port=5432"
networks:
backend:
external: true
volumes:
postgresql-data:
It seems my Traefik configuration is correct. Everything is OK in the logs and all sections in dashboard are flagged as Success (no Warnings, no Errors). So I am confident with the Traefik configuration above. The complete flow is about:
EntryPoint(':5432') -> HostSNI(`example.com`) -> TcpRouter(`postgres`) -> Service(`postgres@docker`)
But, it may have a limitation at PostgreSQL side.
Debug
The problem is that I cannot connect the PostgreSQL database. I always get a Timeout error.
I have checked PostgreSQL is listening properly (main cause of Timeout error):
# - Connection Settings -
listen_addresses = '*'
port = 5432
And I checked that I can connect PostgreSQL on the host (outside the container):
psql --host 172.19.0.4 -U postgres
Password for user postgres:
psql (12.2 (Ubuntu 12.2-4), server 12.3 (Debian 12.3-1.pgdg100+1))
Type "help" for help.
postgres=#
Thus I know PostgreSQL is listening outside its container, so Traefik should be able to bind the flow.
I also have checked external traefik can reach the server:
sudo tcpdump -i ens3 port 5432
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on ens3, link-type EN10MB (Ethernet), capture size 262144 bytes
09:02:37.878614 IP x.y-z-w.isp.com.61229 > example.com.postgresql: Flags [S], seq 1027429527, win 64240, options [mss 1452,nop,wscale 8,nop,nop,sackOK], length 0
09:02:37.879858 IP example.com.postgresql > x.y-z-w.isp.com.61229: Flags [S.], seq 3545496818, ack 1027429528, win 64240, options [mss 1460,nop,nop,sackOK,nop,wscale 7], length 0
09:02:37.922591 IP x.y-z-w.isp.com.61229 > example.com.postgresql: Flags [.], ack 1, win 516, length 0
09:02:37.922718 IP x.y-z-w.isp.com.61229 > example.com.postgresql: Flags [P.], seq 1:9, ack 1, win 516, length 8
09:02:37.922750 IP example.com.postgresql > x.y-z-w.isp.com.61229: Flags [.], ack 9, win 502, length 0
09:02:47.908808 IP x.y-z-w.isp.com.61229 > example.com.postgresql: Flags [F.], seq 9, ack 1, win 516, length 0
09:02:47.909578 IP example.com.postgresql > x.y-z-w.isp.com.61229: Flags [P.], seq 1:104, ack 10, win 502, length 103
09:02:47.909754 IP example.com.postgresql > x.y-z-w.isp.com.61229: Flags [F.], seq 104, ack 10, win 502, length 0
09:02:47.961826 IP x.y-z-w.isp.com.61229 > example.com.postgresql: Flags [R.], seq 10, ack 104, win 0, length 0
So, I am wondering why the connection cannot succeed. Something must be wrong between Traefik and PostgreSQL.
SNI incompatibility?
Even when I remove the TLS configuration, the problem is still there, so I don't expect the TLS to be the origin of this problem.
Then I searched and I found few posts relating similar issue:
Introducing SNI in TLS handshake for SSL connections
Traefik 2.0 TCP routing for multiple DBs;
As far as I understand it, the SSL protocol of PostgreSQL is a custom one and does not support SNI for now and might never support it. If it is correct, it will confirm that Traefik cannot proxy PostgreSQL for now and this is a limitation.
By writing this post I would like to confirm my observations and at the same time leave a visible record on Stack Overflow to anyone who faces the same problem and seek for help. My question is then: Is it possible to use Traefik to proxy PostgreSQL?
Update
Intersting observation, if using HostSNI('*') and Let's Encrypt:
labels:
- "traefik.enable=true"
- "traefik.docker.network=backend"
- "traefik.tcp.routers.postgres.entrypoints=postgres"
- "traefik.tcp.routers.postgres.rule=HostSNI(`*`)"
- "traefik.tcp.routers.postgres.tls=true"
- "traefik.tcp.routers.postgres.tls.certresolver=lets"
- "traefik.tcp.services.postgres.loadBalancer.server.port=5432"
Everything is flagged as success in Dashboard but of course Let's Encrypt cannot perform the DNS Challenge for wildcard *, it complaints in logs:
time="2020-08-12T10:25:22Z" level=error msg="Unable to obtain ACME certificate for domains \"*\": unable to generate a wildcard certificate in ACME provider for domain \"*\" : ACME needs a DNSChallenge" providerName=lets.acme routerName=postgres@docker rule="HostSNI(`*`)"
When I try the following configuration:
labels:
- "traefik.enable=true"
- "traefik.docker.network=backend"
- "traefik.tcp.routers.postgres.entrypoints=postgres"
- "traefik.tcp.routers.postgres.rule=HostSNI(`*`)"
- "traefik.tcp.routers.postgres.tls=true"
- "traefik.tcp.routers.postgres.tls.domains[0].main=example.com"
- "traefik.tcp.routers.postgres.tls.certresolver=lets"
- "traefik.tcp.services.postgres.loadBalancer.server.port=5432"
The error vanishes from logs and in both setups the dashboard seems ok but traffic is not routed to PostgreSQL (time out). Anyway, removing SSL from the configuration makes the flow complete (and unsecure):
labels:
- "traefik.enable=true"
- "traefik.docker.network=backend"
- "traefik.tcp.routers.postgres.entrypoints=postgres"
- "traefik.tcp.routers.postgres.rule=HostSNI(`*`)"
- "traefik.tcp.services.postgres.loadBalancer.server.port=5432"
Then it is possible to connect PostgreSQL database:
time="2020-08-12T10:30:52Z" level=debug msg="Handling connection from x.y.z.w:58389"
| SNI routing for postgres with STARTTLS has been added to Traefik in this PR. Now Treafik will listen to the initial bytes sent by postgres and if its going to initiate a TLS handshake (Note that postgres TLS requests are created as non-TLS first and then upgraded to TLS requests), Treafik will handle the handshake and then is able to receive the TLS headers from postgres, which contains the SNI information that it needs to route the request properly. This means that you can use HostSNI("example.com") along with tls to expose postgres databases under different subdomains.
As of writing this answer, I was able to get this working with the v3.0.0-beta2 image (Reference)
| Traefik | 63,354,909 | 18 |
So I'm trying to set up a gitlab-ce instance on docker swarm using traefik as reverse proxy.
This is my proxy stack;
version: '3'
services:
traefik:
image: traefik:alpine
command: --entryPoints="Name:http Address::80 Redirect.EntryPoint:https" --entryPoints="Name:https Address::443 TLS" --defaultentrypoints="http,https" --acme --acme.acmelogging="true" --acme.email="[email protected]" --acme.entrypoint="https" --acme.storage="acme.json" --acme.onhostrule="true" --docker --docker.swarmmode --docker.domain="mydomain.com" --docker.watch --web
ports:
- 80:80
- 443:443
- 8080:8080
networks:
- traefik-net
volumes:
- /var/run/docker.sock:/var/run/docker.sock
deploy:
placement:
constraints:
- node.role == manager
networks:
traefik-net:
external: true
And my gitlab stack
version: '3'
services:
omnibus:
image: 'gitlab/gitlab-ce:latest'
hostname: 'lab.mydomain.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
external_url 'https://lab.mydomain.com'
nginx['listen_port'] = 80
nginx['listen_https'] = false
registry_external_url 'https://registry.mydomain.com'
registry_nginx['listen_port'] = 80
registry_nginx['listen_https'] = false
gitlab_rails['gitlab_shell_ssh_port'] = 2222
gitlab_rails['gitlab_email_from'] = '[email protected]'
gitlab_rails['gitlab_email_reply_to'] = '[email protected]'
ports:
- 2222:22
volumes:
- gitlab_config:/etc/gitlab
- gitlab_logs:/var/log/gitlab
- gitlab_data:/var/opt/gitlab
networks:
- traefik-net
deploy:
labels:
traefik.enable: "port"
traefik.frontend.rule: 'Host: lab.mydomain.com, Host: registry.mydomain.com'
traefik.port: 80
placement:
constraints:
- node.role == manager
runner:
image: 'gitlab/gitlab-runner:v1.11.4'
volumes:
- gitlab_runner_config:/etc/gitlab-runner
- /var/run/docker.sock:/var/run/docker.sock
volumes:
gitlab_config:
gitlab_logs:
gitlab_data:
gitlab_runner_config:
networks:
traefik-net:
external: true
traefik-net is an overlay network
So when I deploy using docker stack deploy and visit lab.mydomain.com, i get the Gateway Timeout error. When I execute curl localhost within the gitlab container, it seems to work fine. Not sure what the problem is, any pointers would be appreciated
| Turns out all I had to do was set the traefik label, traefik.docker.network to traefik-net, see https://github.com/containous/traefik/issues/1254
| Traefik | 46,698,425 | 16 |
According to the Traefik 1.7 documentation you should be able to have Traefik perform a 302 redirect using:
traefik.ingress.kubernetes.io/redirect-regex
traefik.ingress.kubernetes.io/redirect-replacement
My goal is to simply remove the www. from the address.
This is what I've tried, but I get a 404 service not found.
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: www-redirect
namespace: public
annotations:
kubernetes.io/ingress.class: traefik
traefik.ingress.kubernetes.io/redirect-regex: ^https?://www.example.com/(.*)
traefik.ingress.kubernetes.io/redirect-replacement: https://example.com/$1
spec:
rules:
- host: www.example.com
Unfortunately the documentation isn't explicit on how to use them. At the time of writing the only google hit on this is the documentation (above).
My current work around (assuming it'll help explain the question) is to route www. traffic to nginx which returns a 302.
server {
listen 80;
server_name www.example.com;
return 302 https://example.com$request_uri;
}
This seems like overkill.
| I was having the same issue and ended up making it work with:
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: www-redirect
namespace: public
annotations:
kubernetes.io/ingress.class: traefik
traefik.ingress.kubernetes.io/preserve-host: "true"
traefik.ingress.kubernetes.io/redirect-permanent: "true"
traefik.ingress.kubernetes.io/redirect-regex: "^https://www.(.*)"
traefik.ingress.kubernetes.io/redirect-replacement: "https://$1"
spec:
tls:
- hosts:
- "example.com"
- "www.example.com"
secretName: example-tls
rules:
- host: example.com
- host: www.example.com
Basically I needed both rules.
As a side note, I also start the trafik pod with the following flags:
args:
- --api
- --kubernetes
- --logLevel=INFO
- --entryPoints=Name:https Address::443 TLS
- --entrypoints=Name:http Address::80 Redirect.EntryPoint:https
- --defaultentrypoints=https,http
| Traefik | 48,627,768 | 16 |
I'm interested in setting up fail2ban with my Traefik deployment. I found a gist that has some snippets in it, but I'm not clear on how to use them. Can anyone fill in the blanks please? Or, is there a better way to implement fail2ban style security with Traefik?
| I was able to accomplish this starting with the gist you posted. This is under the assumptions you have Traefik already working, want to block IPs that have HTTP Basic Auth failures, and ban them with iptables. There's a couple of pieces so let me start with the container configurations:
Traefik docker-compose.yaml
version: '2'
services:
traefik:
image: traefik:alpine
volumes:
- /apps/docker/traefik/traefik.toml:/traefik.toml:ro
- /apps/docker/traefik/acme:/etc/traefik/acme
- /var/log/traefik:/var/log
ports:
- 8080:8080/tcp
- 80:80/tcp
- 443:443/tcp
command:
- --web
- --accessLog.filePath=/var/log/access.log
- --accessLog.filters.statusCodes=400-499
You can see here I am writing the log file to /var/log/access.log and only getting access codes to 400-499. I am then mounting that file to my host /var/log/traefik:/var/log
Now for the fail2ban part, I am using a fail2ban docker container rather than installing on my host, but you could technically do it there too.
Fail2ban docker-compose.yaml
version: '2'
services:
fail2ban:
image: crazymax/fail2ban:latest
network_mode: "host"
cap_add:
- NET_ADMIN
- NET_RAW
volumes:
- /var/log:/var/log:ro
- /apps/docker/fail2ban/data:/data
You can see I mount the /var/log directory into the fail2ban container as read only.
Fail2ban configuration
The /apps/docker/fail2ban/data/jail.d/traefik.conf file contains:
[traefik-auth]
enabled = true
logpath = /var/log/traefik/access.log
port = http,https
The /apps/docker/fail2ban/data/filter.d/traefik-auth.conf file contains:
[Definition]
failregex = ^<HOST> \- \S+ \[\] \"(GET|POST|HEAD) .+\" 401 .+$
ignoreregex =
Extra
The default ban action is to ban via iptables. If you want to change that you can change the default banaction in the traefik.conf, for example:
[DEFAULT]
banaction = cloudflare
[traefik-auth]
enabled = true
logpath = /var/log/traefik/access.log
port = http,https
Actions are here: https://github.com/fail2ban/fail2ban/tree/0.11/config/action.d
If you need to modify one, copy the file to the /apps/docker/fail2ban/data/action.d directory and restart the container.
| Traefik | 52,123,355 | 16 |
Do you happen to know where the Traefik logs are located? I read the documentation on Traefik and it says it will output to stdout but when I start the docker container with docker-compose up -d it doesn't show anything in stdout after I try the domain name and pull up multiple linked docker containers.
I also tried to specify these:
[traefikLog]
filePath = "./traefik.log" #<--Tried this but It doesn't work, file empty and permissions set to 777
[accessLog]
filePath = "./access.log" #<--Tried this but doesn't work, file empty and permissions set to 777
I'm confused, am I missing something? or is Traefik supposed to be this quiet?
When I run it this is all I see, nothing afterwards.
# docker-compose up
Creating traefik ... done
Attaching to traefik
Attached is my config. Thanks.
traefik/traefik.toml:
logLevel = "DEBUG"
defaultEntryPoints = ["http","https"]
[api]
address = ":8080"
[traefikLog]
filePath = "./traefik.log" #<--Tried this but It doesn't work
[accessLog]
filePath = "./access.log" #<--Tried this but doesn't work
[entryPoints]
[entryPoints.http]
#redirect ALL http traffic to https 443
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
#Let's encrypt setup
[acme]
email = "[email protected]"
storage = "acme.json"
entryPoint = "https"
acmeLogging = true
#When new host is created, request certificate.
onHostRule = true
onDemand = false
[acme.httpChallenge]
entryPoint = "http"
#Watch Docker, when new containers are created with label create mapping.
[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "exampledomain.net"
watch = true
exposedbydefault = false
docker-compose.yml:
version: '3'
services:
traefik:
hostname: traefik
domainname: exampledomain.net
image: traefik:alpine
command: --api --docker
container_name: traefik
networks:
- nginx-proxy
ports:
- "80:80"
- "443:443"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock"
- "./traefik/traefik.toml:/traefik.toml"
- "./traefik/acme.json:/acme.json"
labels:
- "traefik.enable=true"
- "traefik.port=8080"
- "traefik.frontend.rule=Host:monitor.exampledomain.net"
- "traefik.docker.network=nginx-proxy"
networks:
nginx-proxy:
external:
name: nginx-proxy
| To see logs in the stdout event if you run docker-compose up -d:
docker-compose logs -f
https://docs.docker.com/compose/reference/logs/
FYI The path ./traefik.log is inside the Traefik container.
[traefikLog]
filePath = "./traefik.log"
With your files (without the section [traefikLog]), I see the logs.
However, your configuration have some issues:
version: '3'
services:
traefik:
hostname: traefik
domainname: exampledomain.net
image: traefik:v1.7.9-alpine
# command: --api --docker # <-- don't define the same configuration with CLI and TOML https://docs.traefik.io/basics/#static-traefik-configuration
container_name: traefik
networks:
- nginx-proxy
ports:
- "80:80"
- "443:443"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock"
- "./traefik/traefik.toml:/traefik.toml"
- "./traefik/acme.json:/acme.json"
labels:
- "traefik.enable=true"
- "traefik.port=8080"
- "traefik.frontend.rule=Host:monitor.exampledomain.net"
- "traefik.docker.network=nginx-proxy"
networks:
nginx-proxy:
external:
name: nginx-proxy
logLevel = "DEBUG"
defaultEntryPoints = ["http","https"]
[api]
# address = ":8080" <- this options doesn't exist. https://docs.traefik.io/v1.7/configuration/api/
# [traefikLog] # <-- remove because not needed
# filePath = "./traefik.log"
# [accessLog] # <-- remove because not needed
# filePath = "./access.log"
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
# Let's encrypt setup
[acme]
email = "[email protected]"
storage = "acme.json"
entryPoint = "https"
acmeLogging = true
onHostRule = true
onDemand = false
[acme.httpChallenge]
entryPoint = "http"
[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "exampledomain.net"
# watch = true # <---- useful only for swarm
exposedbydefault = false
| Traefik | 54,776,024 | 16 |
I did search the manual but really couldn't make it very clear, even using the keywords to google that.
I need to proxy the /_ to the API container, some rule like that www.mydomain.com/_ => API container
There is already a specified domain point to this API container
api.mydomain.com => API container
This is my docker-compose.yml, all I want is to add a rule that proxy the /_ to this container too.
version: '3.3'
services:
testapi:
image: git.xxxx.com/api/core/test:latest
restart: always
networks:
- web
- default
expose:
- "80"
labels:
- "traefik.enable=true"
- "traefik.port=80"
- "traefik.docker.network=web"
- "traefik.backend=testapi"
#this domain is used for app
- "traefik.frontend.rule=Host:api.test.mydomain.com"
#this is used for website.All I want is prxy "https://www.test.mydomain.com/_/" to this container
- "traefik.frontend.rule1=Host:www.test.mydomain.com;PathPrefixStrp:/_"
| You can use segment labels:
version: '3.3'
services:
testapi:
image: git.xxxx.com/api/core/test:latest
restart: always
networks:
- web
- default
expose:
- "80"
labels:
- "traefik.enable=true"
- "traefik.port=80"
- "traefik.docker.network=web"
#this domain is used for app
- "traefik.foo.frontend.rule=Host:api.test.mydomain.com"
- "traefik.bar.frontend.rule=Host:www.test.mydomain.com,m.test.mydomain.com;PathPrefixStrp:/_"
https://docs.traefik.io/v1.6/configuration/backends/docker/#on-containers-with-multiple-ports-segment-labels
| Traefik | 52,240,784 | 15 |
I am trying to use Traefik to deploy proxy multiple applications in my Docker Swarm mode cluster.
I have got it so that it proxies a named Host but I want it to proxy on a named Host and Path, but I cannot work out the labels I need to use.
This is the docker service command I am using:
docker service create \
\
--label "traefik.port=9000" \
--label "traefik.docker.network=traefik-net" \
--label "traefik.frontend.rule=Host:`hostname -f`" \
--label="traefik.backend=portainer" \
\
--constraint "node.role == manager" \
-p 9000:9000 \
--mount "type=bind,src=/var/run/docker.sock,dst=/var/run/docker.sock" \
--name portainer \
portainer/portainer
If the host is dummy.localhost then I am able to hit the portainer app on http://dummy.localhost. However I want to modify it so that I have to use http://dummy.localhost/portainer.
I have seen that there are ways to do this when using a toml file for Traefik, but I am using watch mode and labels on the docker services I deploy.
How can I combine multiple front end rules in my labels so that this (and any other) application can be proxied on a hostname and a path?
| Traefik v1
If you want multiple rules to apply in order for a routing decision to become effective, separate them by semicolon. For instance:
Host: <your host rule>; PathPrefixStrip: /portainer
What the above means is: If the host and path prefix match, Traefik will route requests to the associated backend(s) (and strip off the specified path prefix prior to forwarding). This even works when defined inside a label.
See the frontend documentation for details.
Update: Traefik v2
Host(`domain.com`) && Path(`/path`)
See the docs
| Traefik | 44,232,354 | 14 |
I want Ingress to redirect a specific subdomain to one backend and all others to other backend. Basically, I want to define a rule something like the following:
If subdomain is foo.bar.com then go to s1, for all other subdomains go to s2
When I define the rules as shown below in the Ingress spec, I get this exception at deployment:
Error: UPGRADE FAILED: cannot re-use a name that is still in use
When I change *.bar.com to demo.bar.com it works, however.
Here's my Ingress resource spec:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: test
spec:
rules:
- host: foo.bar.com
http:
paths:
- backend:
serviceName: s1
servicePort: 80
- host: *.bar.com
http:
paths:
- backend:
serviceName: s2
servicePort: 80
Anyone has an idea if it is possible or not?
| This is now possible in Kubernetes with nginx:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
ingress.kubernetes.io/ssl-redirect: "false"
kubernetes.io/ingress.class: nginx
kubernetes.io/ingress.global-static-ip-name: web-static-ip
nginx.ingress.kubernetes.io/rewrite-target: /$1
nginx.ingress.kubernetes.io/server-alias: www.foo.bar
nginx.ingress.kubernetes.io/use-regex: "true"
name: foo-bar-ingress
namespace: test
spec:
rules:
- host: 'foo.bar.com'
http:
paths:
- backend:
serviceName: specific-service
servicePort: 8080
path: /(.*)
pathType: ImplementationSpecific
- host: '*.bar.com'
http:
paths:
- backend:
serviceName: general-service
servicePort: 80
path: /(.*)
pathType: ImplementationSpecific
| Traefik | 52,328,483 | 14 |
Currently I'm trying set up a loadbalancer/reverse proxy with Traefik for some docker containers. I'm having trouble with configuring Treafik to make my apps available using a some prefix paths. I'm able to get a basic Traefik configuration running using Docker and Docker compose, based on this example. The problem is that I'm able to get the 'whoamI' container to be reachable at a path, but not my app and other containers.
For example, I've created a docker-compose file (see below) to start the whoamI container, and five Portainer containers (so people can recreate the scenario). I would expect woamI to be available at /wai and Portainer at /portainer1.
Instead, I can reach the whoamI webserver (via /wai) and not Portainer (via /portainer1). However, I am able to reach Portainer at /portainer2. The only difference in Traefik configuration between these two is the use of 'PathStrip' instead of 'Path'. The annoying thing, however, is that I can only obtain a white page when navigating to /portainer2; only the page title and some html is loaded. I have also started a Portainer container which is exposed to the host machine, to verify the expected behavior (a normal Portainer page). See also the attached image below.
Edit:
Interestingly, I'm also able to reach Portainer at /portainer4/ (but not /portainer4) resulting in the same white page. The difference between navigating to /portainer2/ and /portainer4/ is that I notice some additional logging in Traefik (see below). When navigating to Portainer via /portainer4/, three extra lines show up in the log indicating a 400 status. After some investigation, I found out that this comes from my browser's attempt to load additional files (i.e. a javascript file, a favicon and a stylesheet). So, when accessing Portainer at /portainer4/ my browser knows it needs to fetch those extra files and tries to do so (which does not happen when navigating to /portainer2). When trying to access the files myself by, for example, navigating to /portainer4/ico/favicon.ico, I get a 400 Bad Request. Lastly, when navigating to /portainer2/ico/favicon.ico is see a 404 page not found.
Based on these results I'm wondering:
Why I cannot reach Portainer at /portainer1 but instead on
/portainer2?
Why I do not see the full Portainer page when navigating to
/portainer2?
Why there is a difference in behavior between accessing a file (e.g. the favicon) between /portainer2/ and /portainer4/
What the 400 Bad Request actually means and if/how this problem this problem can be fixed
I would really appreciate some pointers in the right direction
Some screenshots:
docker-compose.yml:
version: '2'
services:
traefik:
container_name: traefik
image: traefik
command: --web --docker --docker.domain=docker.localhost --logLevel=DEBUG
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /dev/null:/traefik.toml
labels:
- "traefik.enable=false"
whoami:
image: emilevauge/whoami
labels:
- "traefik.backend=whoami"
- "traefik.frontend.rule=Path: /wai/"
portainer1:
image: portainer/portainer
labels:
- "traefik.backend=portainer1"
- "traefik.frontend.rule=Path: /portainer1/"
portainer2:
image: portainer/portainer
labels:
- "traefik.backend=portainer2"
- "traefik.frontend.rule=PathStrip: /portainer2/"
portainer:
image: portainer/portainer
ports:
- "9000:9000"
labels:
- "traefik.enable=false"
Additional Traefik logging generated after visiting /wai, /portainer1/, <myIP>/portainer2/, /portainer3/ and /portainer4/, respectively:
time="2017-01-13T14:33:16Z" level=debug msg="Round trip: http://172.19.0.2:80, code: 200, duration: 1.000627ms"
time="2017-01-13T14:33:22Z" level=debug msg="Round trip: http://172.19.0.7:9000, code: 404, duration: 1.006089ms"
time="2017-01-13T14:33:24Z" level=debug msg="Round trip: http://172.19.0.3:9000, code: 200, duration: 1.160158ms"
time="2017-01-13T14:33:26Z" level=debug msg="Round trip: http://172.20.0.5:9000, code: 404, duration: 1.291309ms"
time="2017-01-13T14:33:29Z" level=debug msg="Round trip: http://172.20.0.4:9000, code: 200, duration: 2.788462ms"
time="2017-01-13T14:33:29Z" level=debug msg="Round trip: http://172.20.0.4:9000, code: 400, duration: 777.073Β΅s"
time="2017-01-13T14:33:30Z" level=debug msg="Round trip: http://172.20.0.4:9000, code: 400, duration: 1.780621ms"
time="2017-01-13T14:33:30Z" level=debug msg="Round trip: http://172.20.0.4:9000, code: 400, duration: 1.780341ms"
| This morning I found the solution. The correct approach in cases like these should be to use the PathPrefixStrip rule. However, as mentioned here, putting a / at the end of the rule will break the setup. I created a working configuration by removing / at the end of the PathPrefixStrip: /portainer4/ rule. So this docker-compose configuration worked for me:
version: '2'
services:
traefik:
container_name: traefik2
image: traefik
command: --web --docker --docker.domain=docker.localhost --logLevel=DEBUG
ports:
- "80:80"
- "8081:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /dev/null:/traefik.toml
labels:
- "traefik.enable=false"
portainer:
image: portainer/portainer
labels:
- "traefik.backend=portainer"
- "traefik.frontend.rule=PathPrefixStrip: /portainer"
Now when I navigate to <myIP>/portainer/ I see the portainer page. I do, however, still get the white page as mentioned earlier when I navigate to <myIP>/portainer.
| Traefik | 41,637,806 | 13 |
How do I enable log rotation for log files e.g. access.log.
Is this built in ?
Docs only say "This allows the logs to be rotated and processed by an external program, such as logrotate"
| If you are running Traefik in a Docker container then you can do something like this:
Check that logrotate is installed on the Docker host:
logrotate --version
Create file in /etc/logrotate.d/:
vi /etc/logrotate.d/traefik
Put the following script, do not forget to fill with the container name.
/var/log/traefik/*.log {
size 10M
rotate 5
missingok
notifempty
postrotate
docker kill --signal="USR1" <container-name>
endscript
}
Run!
logrotate /etc/logrotate.conf --debug
logrotate /etc/logrotate.conf
| Traefik | 49,450,422 | 13 |
I am trying to configure Basic Authentication on a Nginx example with Traefik as Ingress controller.
I just create the secret "mypasswd" on the Kubernetes secrets.
This is the Ingress I am using:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: nginxingress
annotations:
ingress.kubernetes.io/auth-type: basic
ingress.kubernetes.io/auth-realm: traefik
ingress.kubernetes.io/auth-secret: mypasswd
spec:
rules:
- host: nginx.mycompany.com
http:
paths:
- path: /
backend:
serviceName: nginxservice
servicePort: 80
I check in the Traefik dashboard and it appear, if I access to nginx.mycompany.com I can check the Nginx webpage, but without the basic authentication.
This is my nginx deployment:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.7.9
ports:
- containerPort: 80
Nginx service:
apiVersion: v1
kind: Service
metadata:
labels:
name: nginxservice
name: nginxservice
spec:
ports:
# The port that this service should serve on.
- port: 80
# Label keys and values that must match in order to receive traffic for this service.
selector:
app: nginx
type: ClusterIP
| It is popular to use basic authentication. In reference to Kubernetes documentation, you should be able to protect access to Traefik using the following steps :
Create authentication file using htpasswd tool. You'll be asked for a password for the user:
htpasswd -c ./auth
Now use kubectl to create a secret in the monitoring namespace using the file created by htpasswd.
kubectl create secret generic mysecret --from-file auth
--namespace=monitoring
Enable basic authentication by attaching annotations to Ingress object:
ingress.kubernetes.io/auth-type: "basic"
ingress.kubernetes.io/auth-secret: "mysecret"
So, full example config of basic authentication can looks like:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: prometheus-dashboard
namespace: monitoring
annotations:
kubernetes.io/ingress.class: traefik
ingress.kubernetes.io/auth-type: "basic"
ingress.kubernetes.io/auth-secret: "mysecret"
spec:
rules:
- host: dashboard.prometheus.example.com
http:
paths:
- backend:
serviceName: prometheus
servicePort: 9090
You can apply the example as following:
kubectl create -f prometheus-ingress.yaml -n monitoring
This should work without any issues.
| Traefik | 50,130,797 | 13 |
I have read the documentation but I can not figure out how to configure Traefik v2 to replace Nginx as a reverse proxy for web sites (virtual hosts) without involving Docker. Ideally there would be let'sencrypt https as well.
I have a service running at http://127.0.0.1:4000 which I would like to reverse proxy to from http://myhost.com:80
This is the configuration i've come up with so far:
[Global]
checkNewVersion = true
[log]
level = "DEBUG"
filePath = "log-file.log"
[accessLog]
filePath = "log-access.log"
bufferingSize = 100
[entrypoints]
[entrypoints.http]
address = ":80"
[http]
[http.routers]
[http.routers.my-router]
rule = "Host(`www.myhost.com`)"
service = "http"
entrypoint=["http"]
[http.services]
[http.services.http.loadbalancer]
[[http.services.http.loadbalancer.servers]]
url = "http://127.0.0.1:4000"
| I figured it out,
the first part to note is that in traefik v2 there are two types of configuration, static and dynamic. So I created two files, traefik.toml and traefik-dynamic.toml.
contents of traefik.toml:
[log]
level = "DEBUG"
filePath = "log-file.log"
[accessLog]
filePath = "log-access.log"
bufferingSize = 100
[providers]
[providers.file]
filename = "traefik-dynamic.toml"
[api]
dashboard = true
debug = true
[entryPoints]
[entryPoints.web]
address = ":80"
[entryPoints.web-secure]
address = ":443"
[entryPoints.dashboard]
address = ":8080"
[certificatesResolvers.sample.acme]
email = "[email protected]"
storage = "acme.json"
[certificatesResolvers.sample.acme.httpChallenge]
# used during the challenge
entryPoint = "web"
traefik-dynamic.toml:
[http]
# Redirect to https
[http.middlewares]
[http.middlewares.test-redirectscheme.redirectScheme]
scheme = "https"
[http.routers]
[http.routers.my-router]
rule = "Host(`www.example.com`)"
service = "phx"
entryPoints = ["web-secure"]
[http.routers.my-router.tls]
certResolver = "sample"
[http.services]
[http.services.phx.loadbalancer]
[[http.services.phx.loadbalancer.servers]]
url = "http://127.0.0.1:4000"
| Traefik | 58,496,270 | 13 |
I have the problem that I can route HTTPS traffic but I can not globally redirect the HTTP traffic to HTTPS. In my case I only want HTTPS traffic, so that I want to redirect all the incoming traffic.
Currently I get an 404 error while I try to serve my URLs over HTTP.
I already enabled DEBUG logs in Treafik, but I can not see any problems or unnormal stuff in the logs.
Additionally I saw a pretty similar topic here on Stackoverflow, but we found out, that his error was not the same to mine: How to redirect http to https with Traefik 2.0 and Docker Compose labels?
The following setup is based on the blog entry here: https://blog.containo.us/traefik-2-0-docker-101-fc2893944b9d
My setup
I configured Traefik in my swarm like this:
global:
checkNewVersion: false
sendAnonymousUsage: false
api:
dashboard: true
entryPoints:
web:
address: :80
websecure:
address: :443
providers:
providersThrottleDuration: 2s
docker:
watch: true
endpoint: unix:///var/run/docker.sock
swarmMode: true
swarmModeRefreshSeconds: 15s
exposedByDefault: false
network: webgateway
log:
level: DEBUG
accessLog: {}
certificatesResolvers:
default:
acme:
email: {email}
storage: /etc/traefik/acme/acme.json
httpChallenge:
entryPoint: web
And started Traefik with the following docker-compose file
version: '3'
services:
proxy:
image: traefik:latest
ports:
- "80:80"
- "443:443"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /data/docker_data/traefik/traefik-2.yml:/etc/traefik/traefik.yml
- /data/docker_data/traefik/acme-2.json:/etc/traefik/acme/acme.json
labels:
# redirect
- "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
- "traefik.http.routers.redirs.rule=hostregexp(`{host:.+}`)"
- "traefik.http.routers.redirs.entrypoints=web"
- "traefik.http.routers.redirs.middlewares=redirect-to-https"
My services are configured with the following labels:
traefik.http.routers.myapp.rule=Host(`myapp.ch`)
traefik.http.routers.myapp.service=myapp
traefik.http.routers.myapp.entrypoints=websecure
# I don't think that the following one is required here...
# traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https
traefik.http.routers.myapp.tls.certresolver=default
traefik.http.services.myapp.loadbalancer.server.port=3000
traefik.http.routers.myapp.tls=true
traefik.enable=true
Any ideas why this is not working?
| You don't need to configure the Traefik service itself. On Traefik you only need to have entrypoints to :443 (websecure) and :80 (web)
Because Traefik only acts as entryPoint and will not do the redirect, the middleware on the target service will do that.
Now configure your target service as the following:
version: '2'
services:
mywebserver:
image: 'httpd:alpine'
container_name: mywebserver
labels:
- traefik.enable=true
- traefik.http.middlewares.mywebserver-redirect-websecure.redirectscheme.scheme=https
- traefik.http.routers.mywebserver-web.middlewares=mywebserver-redirect-websecure
- traefik.http.routers.mywebserver-web.rule=Host(`sub.domain.com`)
- traefik.http.routers.mywebserver-web.entrypoints=web
- traefik.http.routers.mywebserver-websecure.rule=Host(`sub.domain.com`)
- traefik.http.routers.mywebserver-websecure.tls.certresolver=mytlschallenge
- traefik.http.routers.mywebserver-websecure.tls=true
- traefik.http.routers.mywebserver-websecure.entrypoints=websecure
# if you have multiple ports exposed on the service, specify port in the websecure service
- traefik.http.services.mywebserver-websecure.loadbalancer.server.port=9000
So basically the flow goes like this:
Request: http://sub.domain.com:80 --> traefik (service) --> mywebserver-web (router, http rule) --> mywebserver-redirect-websecure (middleware, redirect to https) --> mywebserver-websecure (router, https rule) --> mywebserver (service)
| Traefik | 58,666,711 | 12 |
I'm trying to set up Upsource to work behind Traefik: https://www.jetbrains.com/help/upsource/proxy-configuration.html
traefik is listening to port 8008 and 8443 (since 80/443 will be used for another):
--entryPoints='Name:http Address::8008 Redirect.EntryPoint:https' --entryPoints='Name:https Address::8443 TLS'
docker labels:
labels:
traefik.backend: upsource
traefik.enable: "true"
traefik.port: "8080"
traefik.frontend.rule: "Host:review.domain.com"
In conf/internal/bundle.properties, base-url is configured as follow:
base-url=https\://review.domain.com\:8443/
problem:
time="2017-09-20T03:23:59Z" level=error msg="Error getting ACME certificates [review.domain.com] : Cannot obtain certificates map[review.domain.com:acme: Error 400 - urn:acme:error:connection - Connection refused
Error Detail:
Validation for review.domain.com:443
Why it validate for port 443 instead of 8443?
Moreover, to proxy WebSockets in Nginx:
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://upsourcemachine.domain.local:1111;
proxy_pass_header Sec-Websocket-Extensions;
Can you confirm that Traefik support WebSockets? And if so, how to configure?
| Traefik handle websocket, and you don't need any specific configuration for this.
Your problem seems to be more about the challenge in Let's Encrypt.
Let's Encrypt doesn't handle TLS Challenge on other port than the default one and the default challenging in Traefik is TLS :(
So you need to configure Traefik to use DNS Challenge
https://docs.traefik.io/configuration/acme/
| Traefik | 46,313,356 | 11 |
Hello I tried looking at the auth options in the annotations for kubernetes traefik ingress. I couldn't find anything where I could configure Forward Authentication as documented here: https://docs.traefik.io/configuration/entrypoints/#forward-authentication
I would like to be able to configure forward authentication per ingress resource. This is possible in the nginx ingress controller.
Is that supported currently?
| According to the Traefik documentation that feature will be available in version 1.7 of Traefik (currently a release candidate).
Here is a link to the authentication documentation
My guess is that you will need to add the following 2 annotations:
ingress.kubernetes.io/auth-type: forward
ingress.kubernetes.io/auth-url: https://example.com
and probably also the following annotation with the corresponding header fields your auth service returns as value:
ingress.kubernetes.io/auth-response-headers: X-Auth-User, X-Secret
| Traefik | 50,964,605 | 11 |
I'm looking for a recommended configuration for SSL/TLS in Traefik. I have set minVersion = "VersionTLS12" to avoid the weaker older versions and found the supported ciphers in Go. Cross-checking that with the recommendations from SSLLabs I came up with the following sequence (order matters):
cipherSuites = [
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
]
[Update] Later cross-checked with Mozilla's SSL Config Generator, dropping the SHA-1 ones and using the suggested order:
cipherSuites = [
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
]
Does that make sense? I want to avoid weak ciphers, but include as many strong ciphers as possible for compatibility.
| You can use this page to generate your traefik config: https://ssl-config.mozilla.org/#server=traefik&server-version=1.7.12&config=intermediate
# generated 2019-07-17, https://ssl-config.mozilla.org/#server=traefik&server-version=1.7.12&config=intermediate
defaultEntryPoints = ["http", "https"]
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
minVersion = "VersionTLS12"
cipherSuites = [
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
"TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"
]
[[entryPoints.https.tls.certificates]]
certFile = "/path/to/signed_cert_plus_intermediates"
keyFile = "/path/to/private_key"
| Traefik | 52,128,979 | 11 |
I try in a simple way to access traefik via the sub-domain traefik (traefik.DOMAIN.com). As soon as I gain access to it, the SSL Certificate is well functional but impossible to access the dashboard (404 error)
docker-compose.yml
version: '3'
services:
reverse-proxy:
image: traefik:v2.2
container_name: traefik
ports:
- "80:80"
- "443:443"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- $PWD/traefik.toml:/etc/traefik/traefik.toml
- $PWD/acme.json:/acme.json
restart: always
labels:
- "traefik.enable=true"
- "traefik.http.routers.api.rule=Host(`traefik.DOMAIN.com`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))"
- "traefik.http.routers.api.service=api@internal"
- "traefik.http.routers.api.entrypoints=websecure"
networks:
- web
networks:
web:
external: true
traefik.toml
[api]
dashboard = true
[entryPoints]
[entryPoints.web]
address = ":80"
[entryPoints.web.http]
[entryPoints.web.http.redirections]
[entryPoints.web.http.redirections.entryPoint]
to = "websecure"
scheme = "https"
[entryPoints.websecure]
address = ":443"
[entryPoints.websecure.http.tls]
certResolver = "default"
[providers]
[providers.docker]
watch = true
exposedByDefault = false
network = "web"
[certificatesResolvers]
[certificatesResolvers.default]
[certificatesResolvers.default.acme]
email = "[email protected]"
storage = "acme.json"
caServer = "https://acme-v01.api.letsencrypt.org/directory"
[certificatesResolvers.default.acme.tlsChallenge]
Any ideas on how to make this work? I would like to eventually be able to install owncloud on a sub-domain
| After reading the documentation and checking the logs in DEBUG mode I was able to make it work. The key here is the trailing / which is mandatory.
traefik.toml
[entryPoints]
[entryPoints.web]
address = ":80"
[entryPoints.web.http]
[entryPoints.web.http.redirections]
[entryPoints.web.http.redirections.entryPoint]
to = "websecure"
scheme = "https"
[entryPoints.websecure]
address = ":443"
[entryPoints.websecure.http.tls]
certResolver = "default"
[providers]
[providers.docker]
watch = true
exposedByDefault = false
network = "web"
[log]
level = "DEBUG"
[api]
dashboard = true
insecure = false
[accessLog]
[certificatesResolvers]
[certificatesResolvers.default]
[certificatesResolvers.default.acme]
email = "[email protected]"
storage = "acme.json"
caServer = "https://acme-v01.api.letsencrypt.org/directory"
[certificatesResolvers.default.acme.tlsChallenge]
docker-compose.yaml
version: '3'
services:
reverse-proxy:
image: traefik:v2.2
container_name: traefik
ports:
- "80:80"
- "443:443"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- $PWD/traefik.toml:/etc/traefik/traefik.toml
- $PWD/acme.json:/acme.json
restart: always
labels:
- "traefik.enable=true"
- "traefik.http.routers.api.rule=Host(`traefik.mydomain.com`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))"
- "traefik.http.routers.api.service=api@internal"
- "traefik.http.routers.api.entrypoints=websecure"
networks:
- web
networks:
web:
external: true
Files
ls
acme.json docker-compose.yaml traefik.toml
Now consider the following from the official documentation
curl -s -o /dev/null -w "%{http_code}" https://traefik.mydomain.com/dashboard/
200
curl -s -o /dev/null -w "%{http_code}" https://traefik.mydomain.com/dashboard
404
Here is the screenshot
| Traefik | 63,116,661 | 11 |
My goal is to protect the traefik front-end with basic authentication.
I am running Traefik version v1.4.3 built on 2017-11-14_11:14:24AM in a Docker container.
My docker-compose.yml file looks like this:
version: "3"
services:
proxy:
image: traefik
command: --web --docker --docker.domain=docker.localhost --logLevel=DEBUG
ports:
- "80:80"
- "8081:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ~/git/traefik/traefik.toml:/etc/traefik/traefik.toml
- ~/git/traefik/.htpasswd:/etc/traefik/.htpasswd
networks:
default:
external:
name: my_nw
The section for the web frontend in my traefik.toml file looks like this:
....
# Enable web configuration backend
[web]
address = ":8080"
[web.auth.basic]
usersFile = "/etc/traefik/.htpasswd"
...
But my custom traefik.toml file seems not to be mountet/read by traefik - still no authentication necessary for the traefik front-end.
The debug log output looks like this:
$ docker-compose up
Starting traefik_proxy_1
Attaching to traefik_proxy_1
proxy_1 | time="2017-11-20T07:30:10Z" level=info msg="Using TOML configuration file /etc/traefik/traefik.toml"
proxy_1 | time="2017-11-20T07:30:10Z" level=info msg="Traefik version v1.4.3 built on 2017-11-14_11:14:24AM"
proxy_1 | time="2017-11-20T07:30:10Z" level=debug msg="Global configuration loaded {"GraceTimeOut":10000000000,"Debug":false,"CheckNewVersion":true,"AccessLogsFile":"","AccessLog":null,"TraefikLogsFile":"","LogLevel":"DEBUG","EntryPoints":{"http":{"Network":"","Address":":80","TLS":null,"Redirect":null,"Auth":null,"WhitelistSourceRange":null,"Compress":false,"ProxyProtocol":null,"ForwardedHeaders":{"Insecure":true,"TrustedIPs":null}}},"Cluster":null,"Constraints":[],"ACME":null,"DefaultEntryPoints":[],"ProvidersThrottleDuration":2000000000,"MaxIdleConnsPerHost":200,"IdleTimeout":0,"InsecureSkipVerify":false,"RootCAs":null,"Retry":null,"HealthCheck":{"Interval":30000000000},"RespondingTimeouts":null,"ForwardingTimeouts":null,"Docker":{"Watch":true,"Filename":"","Constraints":null,"Trace":false,"DebugLogGeneratedTemplate":false,"Endpoint":"unix:///var/run/docker.sock","Domain":"docker.localhost","TLS":null,"ExposedByDefault":true,"UseBindPortIP":false,"SwarmMode":false},"File":null,"Web":{"Address":":8080","CertFile":"","KeyFile":"","ReadOnly":false,"Statistics":null,"Metrics":null,"Path":"/","Auth":null,"Debug":false,"CurrentConfigurations":null,"Stats":null,"StatsRecorder":null},"Marathon":null,"Consul":null,"ConsulCatalog":null,"Etcd":null,"Zookeeper":null,"Boltdb":null,"Kubernetes":null,"Mesos":null,"Eureka":null,"ECS":null,"Rancher":null,"DynamoDB":null}"
proxy_1 | time="2017-11-20T07:30:10Z" level=info msg="Preparing server http &{Network: Address::80 TLS:<nil> Redirect:<nil> Auth:<nil> WhitelistSourceRange:[] Compress:false ProxyProtocol:<nil> ForwardedHeaders:0xc420270180} with readTimeout=0s writeTimeout=0s idleTimeout=3m0s"
proxy_1 | time="2017-11-20T07:30:10Z" level=info msg="Starting provider *docker.Provider {"Watch":true,"Filename":"","Constraints":null,"Trace":false,"DebugLogGeneratedTemplate":false,"Endpoint":"unix:///var/run/docker.sock","Domain":"docker.localhost","TLS":null,"ExposedByDefault":true,"UseBindPortIP":false,"SwarmMode":false}"
proxy_1 | time="2017-11-20T07:30:10Z" level=info msg="Starting provider *web.Provider {"Address":":8080","CertFile":"","KeyFile":"","ReadOnly":false,"Statistics":null,"Metrics":null,"Path":"/","Auth":null,"Debug":false,"CurrentConfigurations":{},"Stats":{"Uptime":"2017-11-20T07:30:10.282646542Z","Pid":1,"ResponseCounts":{},"TotalResponseCounts":{},"TotalResponseTime":"0001-01-01T00:00:00Z"},"StatsRecorder":null}"
proxy_1 | time="2017-11-20T07:30:10Z" level=info msg="Starting server on :80"
proxy_1 | time="2017-11-20T07:30:10Z" level=debug msg="Provider connection established with docker 17.09.0-ce (API 1.32)"
proxy_1 | time="2017-11-20T07:30:10Z" level=debug msg="Validation of load balancer method for backend backend-proxy-traefik failed: invalid load-balancing method ''. Using default method wrr."
proxy_1 | time="2017-11-20T07:30:10Z" level=debug msg="Configuration received from provider docker: {"backends":{"backend-proxy-traefik":{"servers":{"server-traefik_proxy_1":{"url":"http://172.19.0.2:80","weight":0}},"loadBalancer":{"method":"wrr"}}},"frontends":{"frontend-Host-proxy-traefik-docker-localhost-0":{"backend":"backend-proxy-traefik","routes":{"route-frontend-Host-proxy-traefik-docker-localhost-0":{"rule":"Host:proxy.traefik.docker.localhost"}},"passHostHeader":true,"priority":0,"basicAuth":[],"headers":{}}}}"
proxy_1 | time="2017-11-20T07:30:10Z" level=debug msg="Last docker config received more than 2s, OK"
proxy_1 | time="2017-11-20T07:30:10Z" level=debug msg="Creating frontend frontend-Host-proxy-traefik-docker-localhost-0"
proxy_1 | time="2017-11-20T07:30:10Z" level=error msg="No entrypoint defined for frontend frontend-Host-proxy-traefik-docker-localhost-0, defaultEntryPoints:[]"
proxy_1 | time="2017-11-20T07:30:10Z" level=error msg="Skipping frontend frontend-Host-proxy-traefik-docker-localhost-0..."
proxy_1 | time="2017-11-20T07:30:10Z" level=info msg="Server configuration reloaded on :80"
I followed the docu from here: http://docs.traefik.io/configuration/backends/web/#authentication
I can not see whats wrong with my setup.
| The reason why the setup shown in my own question was not working, was the 'command' entry in my docker-compose.yml file:
command: --web --docker --docker.domain=docker.localhost --logLevel=DEBUG
This command overwrite the [web] and [docker] settings form my traefik.toml file.
So in case when you start traefik as a docker container with docker-compose, the docker-compose.yml file should not! contain any commands if you mount a custom traefik.toml file. In this scenario, all settings should be placed into the trafik.toml file.
So it works with the following docker-compose.yml file:
version: "3"
services:
proxy:
image: traefik
ports:
- "80:80"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- $PWD/traefik.toml:/etc/traefik/traefik.toml
- $PWD/.htpasswd:/etc/traefik/.htpasswd
networks:
default:
external:
name: my_network
Note that the traefik.toml file must be mounted into container directory /etc/traefik/
| Traefik | 47,382,756 | 10 |
I am configuring Traefik to work as a reverse proxy in my development environment. I currently have applications running on different ports, and different PATHs.
My Environment:
Traefik is running on a Host (192.168.0.10). Listening on port 80, 443 and 8080 (traefik dashboard).
My applications are running on a different host (192.168.0.11).
Web application: 192.168.0.11:8200/web1
Backend: 192.168.0.11:8210/api1
Other web application: 192.168.0.11:8300/web2
Other Backend: 192.168.0.11:8310/api2
I want to redirect all these applications through a same subdomain (dev.domain.com) with Traefik + LetsEncrypt (acme).
For example:
When I access dev.domain.com/web1, I want to redirect all access to 192.168.0.11:8200/web1
When I access dev.domain.com/api1, I want to redirect all access to 192.168.0.11:8210/api1
And so on..
Below is the settings I'm using, Traefik version, etc.
traefil.toml
debug = true
logLevel = "DEBUG"
InsecureSkipVerify = false
defaultEntryPoints = ["https", "http"]
[api]
entryPoint = "traefik"
dashboard = true
address = ":8080"
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
[file]
directory = "/etc/traefik/rules.d"
watch = true
[acme]
email = "[email protected]"
storage="/etc/traefik/acme/acme.json"
entryPoint = "https"
acmeLogging=true
onDemand = true
[acme.dnsChallenge]
provider = "godaddy"
delayBeforeCheck = 0
[[acme.domains]]
main = "domain.com"
[[acme.domains]]
main = "*.domain.com"
[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "domain.com"
watch = true
exposedbydefault = false
rules.d directory have multiple .toml files.
web1.toml
loglevel = "ERROR"
[backends]
[backends.web-backend]
[backends.web-backend.servers.backend_web-backend1]
url = "http://192.168.0.11:8200/web1"
[frontends]
[frontends.web-frontend]
backend = "web-backend"
X-Custom-Response-Header = true
SSLRedirect = true
[frontends.web-frontend.routes.frontend_web-frontend1]
rule = "Host:dev.domain.com;PathPrefixStrip:/web1"
web2.toml
loglevel = "ERROR"
[backends]
[backends.web-backend]
[backends.web-backend.servers.backend_web-backend1]
url = "http://192.168.0.11:8300/web2"
[frontends]
[frontends.web-frontend]
backend = "web-backend"
X-Custom-Response-Header = true
SSLRedirect = true
[frontends.web-frontend.routes.frontend_web-frontend1]
rule = "Host:dev.domain.com;PathPrefixStrip:/web2"
api1.toml
loglevel = "ERROR"
[backends]
[backends.api-backend]
[backends.api-backend.servers.backend_api-backend1]
url = "http://192.168.0.11:8210"
[frontends]
[frontends.api-frontend]
backend = "api-backend"
X-Custom-Response-Header = true
SSLRedirect = true
[frontends.api-frontend.routes.frontend_api-frontend1]
rule = "Host:dev.domain.com;PathPrefixStrip:/api1"
api2.toml
loglevel = "ERROR"
[backends]
[backends.api-backend]
[backends.api-backend.servers.backend_api-backend1]
url = "http://192.168.0.11:8310"
[frontends]
[frontends.api-frontend]
backend = "api-backend"
X-Custom-Response-Header = true
SSLRedirect = true
[frontends.api-frontend.routes.frontend_api-frontend1]
rule = "Host:dev.domain.com;PathPrefixStrip:/api2"
acme directory is ok! the certificate is created with no erros!
docker-compose.yml
version: "2.1"
services:
traefik:
hostname: traefik
image: traefik:latest
container_name: traefik
restart: always
domainname: ${DOMAINNAME}
networks:
- default
- traefik_proxy
ports:
- "80:80"
- "443:443"
- "8080:8080"
environment:
- GODADDY_API_KEY=${GODADDY_API_KEY}
- GODADDY_API_SECRET=${GODADDY_API_SECRET}
labels:
- "traefik.enable=true"
- "traefik.backend=traefik"
- "traefik.frontend.rule=Host:traefik.${DOMAINNAME}"
- "traefik.port=8080"
- "traefik.docker.network=traefik_proxy"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- /opt/traefik:/etc/traefik
- /opt/traefik/shared:/shared
helloworld:
image: matheuscarino/simple-nodejs-app:latest
container_name: helloworld
restart: always
volumes:
- /var/run/docker.sock:/var/run/docker.sock
environment:
- FOO=BAR
networks:
- traefik_proxy
labels:
- "traefik.enable=true"
- "traefik.backend=helloworld"
- "traefik.frontend.rule=Host:helloworld.${DOMAINNAME}"
- "traefik.port=3000"
networks:
traefik_proxy:
external:
name: traefik_proxy
default:
driver: bridge
Traefik works fine when I need to redirect requests to applications that are running on the host itself through Docker (via Labels). My helloworld.domain.com application works!
Traefik works fine when I redirect only one application. From the moment I configure the second application in the same subdomain, traefik gets lost in redirects through the PATH.
I searched the internet for use cases like mine, but I did not find people using Traefik to redirect the application outside of the Docker Engine, Kubernetes, etc.
| You need to add this parameter in the frontends "AddPrefix:/myprefix" and remove path in backends URL like this:
(url="http://192.168.0.11:8200/myprefix") to (url="http://192.168.0.11:8200)
You just need move this "path" to "AddPrefix" param in frontends configurations if you have PATH in your URL.
All the other configurations are Ok!!
web1.toml
loglevel = "ERROR"
[backends]
[backends.web-backend]
[backends.web-backend.servers.backend_web-backend1]
url = "http://192.168.0.11:8200"
[frontends]
[frontends.web-frontend]
backend = "web-backend"
X-Custom-Response-Header = true
SSLRedirect = true
[frontends.web-frontend.routes.frontend_web-frontend1]
rule = "Host:dev.domain.com;PathPrefixStrip:/web1;AddPrefix:/web1"
web2.toml
loglevel = "ERROR"
[backends]
[backends.web-backend]
[backends.web-backend.servers.backend_web-backend1]
url = "http://192.168.0.11:8300"
[frontends]
[frontends.web-frontend]
backend = "web-backend"
X-Custom-Response-Header = true
SSLRedirect = true
[frontends.web-frontend.routes.frontend_web-frontend1]
rule = "Host:dev.domain.com;PathPrefixStrip:/web2;AddPrefix:/web2"
api1.toml
loglevel = "ERROR"
[backends]
[backends.api-backend]
[backends.api-backend.servers.backend_api-backend1]
url = "http://192.168.0.11:8210"
[frontends]
[frontends.api-frontend]
backend = "api-backend"
X-Custom-Response-Header = true
SSLRedirect = true
[frontends.api-frontend.routes.frontend_api-frontend1]
rule = "Host:dev.domain.com;PathPrefixStrip:/api1;AddPrefix:/api1"
api2.toml
loglevel = "ERROR"
[backends]
[backends.api-backend]
[backends.api-backend.servers.backend_api-backend1]
url = "http://192.168.0.11:8310"
[frontends]
[frontends.api-frontend]
backend = "api-backend"
X-Custom-Response-Header = true
SSLRedirect = true
[frontends.api-frontend.routes.frontend_api-frontend1]
rule = "Host:dev.domain.com;PathPrefixStrip:/api2;AddPrefix:/api2"
| Traefik | 52,083,071 | 10 |
Yes,
I get this when I try to run traefik with https. Problem is I mount the dir on my Win7 machine but I cant chmod the file.
The mount is working but file permissions are off.
looks like this:
volumes
- d:/docker/traefikcompose/acme/acme.json:/etc/traefik/acme/acme.json:rw
traefik | time="2018-09-04T12:57:11Z" level=error msg="Error
starting provider *acme.Provider: unable to get ACME account :
permissions 777 for /etc/traefik/acme/acme.json are too open, please
use 600"
If I remove the acme.json file I get this:
ERROR: for traefik Cannot start service traefik: b'OCI runtime create
failed: container_linux.go:348: starting container process caused
"process_linux.go:402: container init caused \"rootfs_linux.go:58:
mounting \\\"/d/docker/traefikcompose/acme/acme.json\\\" to
rootfs
\\\"/mnt/sda1/var/lib/docker/aufs/mnt/c84d8644252848bde8f0322bafba3d206513ceb8479eb95aeee0b4cafd4a7251\\\"
at
\\\"/mnt/sda1/var/lib/docker/aufs/mnt/c84d8644252848bde8f0322bafba3d206513ceb8479eb95aeee0b4cafd4a7251/etc/traefik/acme/acme.json\\\"
caused \\\"not a directory\\\"\"": unknown: Are you trying to
mount a directory onto a file (or vice-versa)? Check if the specified
host path exists and is the expected type'
| I did finally find the solution thanks to Cooshals kind help,
we have to ssh into the virtualbox-machine and make the file there, and then point it out right from the docker-compose.yml, in this case I did like this:
docker-machine ssh default
touch /var/acme.json
chmod 600 /var/acme.json
Then in my docker-compose:
volumes:
- /var/:/var/acme.json
Finally in traefik.toml:
[acme]
storage = "acme.json"
| Traefik | 52,167,035 | 10 |
So I am using the helm chart stable/traefik to deploy a reverse proxy to my cluster. I need to customise it beyond what is possible with the variables I can set for the template.
I want to enable the dashboard service while not creating an ingress for it (I set up OpenVPN to access the traefik dashboard only via VPN).
Both dashboard-ingress.yaml and dashboard-service.yaml conditionally include the ingress or the respective service based on the same variable {{- if .Values.dashboard.enabled }}
From my experience I would fork the helm chart and push the customised version to my own repository.
Is there a way to add that customization but keep the original helm chart from the stable repository?
| You don't necessarily have to push to your own repository as you could take the source code and include the chart in your own as source. For example, if you dig into the gitlab chart in their charts dependencies they've included multiple other charts as source their, not packaged .tgz files. That enables you to make changes in the chart within your own source (much as the gitlab guys have). You could get the source using helm fetch stable/traefik --untar
However, including the chart as source is still quite close to forking. If you want to upgrade to get fixes then you still have to reapply your changes. I believe your only other option is to raise the issue on the official chart repo. Perhaps for your case you could suggest to the maintainers that the ingress be included only when .Values.dashboard.enabled and a separate ingress condition is met.
| Traefik | 53,172,597 | 10 |
Recently I am moving a project to Kubernetes and have used Traefik as the ingress controller. For Traefik I have used the Traefik Kubernetes Ingress provider for routing. When I tried to add the Traefik dashboard, I found that seems it can only be added using IngressRoute (ie. using Kubernetes CRD as provider).
I have a few questions:
Is it possible to use Traefik Kubernetes Ingress provider to bring up the dashboard?
Can I use both kubernetesingress and kubernetescrd as provider? Can both Ingress and IngressRoute co-exist?
| So I have solved the Traefik Dashboard problem using Traefik Kubernetes Ingress only, the answer to the first question is 'Yes':
The following is my configuration:
traefik-deployment.yaml
kind: Deployment
apiVersion: apps/v1
metadata:
name: traefik
namespace: ingress-traefik
labels:
app: traefik
spec:
replicas: 1
selector:
matchLabels:
app: traefik
template:
metadata:
labels:
app: traefik
spec:
serviceAccountName: traefik-ingress-controller
containers:
- name: traefik
image: traefik:v2.2
ports:
- name: web
containerPort: 80
- name: websecure
containerPort: 443
- name: admin
containerPort: 8080
args:
- --api
- --api.insecure=true
- --api.dashboard=true
- --providers.kubernetesingress
- --providers.kubernetescrd
- --entrypoints.web.Address=:80
- --entrypoints.websecure.Address=:443
traefik-dashboard-ingress.yaml
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: traefik-dashboard-ingress
namespace: ingress-traefik
annotations:
kubernetes.io/ingress.class: traefik
traefik.ingress.kubernetes.io/router.entrypoints: web, websecure
traefik.ingress.kubernetes.io/router.tls: "true"
traefik.ingress.kubernetes.io/router.middlewares: ingress-traefik-traefikbasicauth@kubernetescrd
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
tls:
- secretName: cert-stage-wildcard
rules:
- host: traefik.your-domain.io
http:
paths:
- path: /
backend:
serviceName: traefik-service
servicePort: 8080
The key to bringing up this is to set api.insecure=true, with this I can port-forward and test the Traefik Dashboard on my localhost, and then route the service through the traefik kubernetes ingress.
Another question (Can I use both kubernetesingress and kubernetescrd as provider) is also confirmed to be 'Yes', as I am now using them together, with kubernetesingress for routing and kubernetescrd on the basicAuth MiddleWare.
But I guess the two routing schemes ingress and ingressRoute may not be able to co-exist as they are both for routing and only one of them will be used by the system when both of them exist. Please correct me if I am wrong.
| Traefik | 64,582,491 | 10 |
I'm new to the docker. Any help and tips are welcome.
Environments:
Windows: Windows 10 Pro 21H1
Docker Desktop: 3.4
I can run hello work example without any issues. But seems like I can't use named piped, can't figure out what is the issue.
Some people mentioned named piped is only available for Windows server, but this blog (https://www.docker.com/blog/docker-windows-server-1709/)clearly mentioned Windows 10 is supported.
docker version output:
β― docker version
Client:
Cloud integration: 1.0.17
Version: 20.10.7
API version: 1.41
Go version: go1.16.4
Git commit: f0df350
Built: Wed Jun 2 12:00:56 2021
OS/Arch: windows/amd64
Context: default
Experimental: true
Server: Docker Engine - Community
Engine:
Version: 20.10.7
API version: 1.41 (minimum version 1.24)
Go version: go1.13.15
Git commit: b0f5bc3
Built: Wed Jun 2 11:56:41 2021
OS/Arch: windows/amd64
Experimental: false
YAML file:
version: "2.4"
services:
traefik:
isolation: ${TRAEFIK_ISOLATION}
image: ${TRAEFIK_IMAGE}
command:
- "--ping"
- "--api.insecure=true"
- "--providers.docker.endpoint=npipe:////./pipe/docker_engine"
- "--providers.docker.exposedByDefault=false"
- "--providers.file.directory=C:/etc/traefik/config/dynamic"
- "--entryPoints.websecure.address=:443"
ports:
- "443:443"
- "8079:8080"
healthcheck:
test: ["CMD", "traefik", "healthcheck", "--ping"]
volumes:
- source: \\.\pipe\docker_engine
target: \\.\pipe\docker_engine
type: npipe
- ./traefik:C:/etc/traefik
depends_on:
id:
condition: service_healthy
cm:
condition: service_healthy
.......
I can create the container if I removed the named pipe in volumes then I got different error:
time="2021-06-17T06:32:13+08:00" level=error msg="Provider connection error error during connect: This error may indicate that the docker daemon is not running.: Get \"http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/version\": open //./pipe/docker_engine: The system cannot find the file specified., retrying in 7.701954985s" providerName=docker
The rest of containers are running Okay.
docker compose up output:
β― docker compose up
[+] Running 10/11
- Network sitecore-xp0_default Created 1.1s
- Container sitecore-xp0_mssql_1 Created 0.5s
- Container sitecore-xp0_solr_1 Created 0.5s
- Container sitecore-xp0_id_1 Created 0.4s
- Container sitecore-xp0_solr-init_1 Created 0.3s
- Container sitecore-xp0_xconnect_1 Created 0.3s
- Container sitecore-xp0_cortexprocessingworker_1 Created 0.6s
- Container sitecore-xp0_xdbautomationworker_1 Created 0.6s
- Container sitecore-xp0_xdbsearchworker_1 Created 0.9s
- Container sitecore-xp0_cm_1 Created 0.9s
- Container sitecore-xp0_traefik_1 Creating 0.2s
Error response from daemon: Unrecognised volume spec: file '\\.\pipe\docker_engine' cannot be mapped. Only directories can be mapped on this platform
| This error occurs when using Docker Compose V2. Turn off the option in Docker Desktop settings or use the CLI command docker-compose disable-v2.
| Traefik | 68,010,612 | 10 |
In order to deal with the microservice architecture, it's often used alongside a Reverse Proxy (such as nginx or apache httpd) and for cross cutting concerns implementation API gateway pattern is used. Sometimes Reverse proxy does the work of API gateway.
It will be good to see clear differences between these two approaches.
It looks like the potential benefit of API gateway usage is invoking multiple microservices and aggregating the results. All other responsibilities of API gateway can be implemented using Reverse Proxy. Such as:
Authentication (It can be done using nginx LUA scripts);
Transport security. It itself Reverse Proxy task;
Load balancing
...
So based on this there are several questions:
Does it make sense to use API gateway and Reverse proxy simultaneously (as example request -> API gateway -> reverse proxy(nginx) -> concrete microservice)? In what cases ?
What are the other differences that can be implemented using API gateway and can't be implemented by Reverse proxy and vice versa?
| It is easier to think about them if you realize they aren't mutually exclusive. Think of an API gateway as a specific type reverse proxy implementation.
In regards to your questions, it is not uncommon to see both used in conjunction where the API gateway is treated as an application tier that sits behind a reverse proxy for load balancing and health checking. An example would be something like a WAF sandwich architecture in that your Web Application Firewall/API Gateway is sandwiched by reverse proxy tiers, one for the WAF itself and the other for the individual microservices it talks to.
Regarding the differences, they are very similar. It's just nomenclature. As you take a basic reverse proxy setup and start bolting on more pieces like authentication, rate limiting, dynamic config updates, and service discovery, people are more likely to call that an API gateway.
| Tyk | 35,756,663 | 173 |
I've created several RESTful microservices and dockerized them. Now I want to have a web-based UI for them and the ability to create users and grant permissions to them to use some of the APIs.
I know that I need some kind of API gateway. My first thought was that I always could do that bruteforce way: create some django app that would serve UI and proxy all request to APIs by hand, but this seems very dull. Maybe there are some alternatives? I've ready about Tyk, but can't find any information about the ability to add users and grant permissions to them.
I probably could create an application that would serve as API gateway and automate proxying of requests by writing some code that would model that. So for example I basically need a mapping between external urls to actual api urls and some authorization logic. Maybe there are already something like that?
| I was looking for something similar, including support for rate limiting, UI console, etc. It boils down to a few freemium tools like:
apigee
mashape
apiary
3scale.net
and a few open source ones:
tyk
kong
ApiAxle
WSO2
API Umbrella
I've decided on tyk since it has a nice UI console and solid docs. All of them were mentioned on Quora, which is nice when you want to go shopping :)
| Tyk | 31,546,631 | 11 |
I'm trying to save a UIImage to NSData and then read the NSData back to a new UIImage in Swift. To convert the UIImage to NSData I'm using the following code:
let imageData: NSData = UIImagePNGRepresentation(myImage)
How do I convert imageData (i.e., NSData) back to a new UIImage?
| UIImage(data:imageData,scale:1.0) presuming the image's scale is 1.
In swift 4.2, use below code for get Data().
image.pngData()
| Swift | 32,297,704 | 172 |
I would like to know if there is currently (at the time of asking, the first Xcode 12.0 Beta) a way to initialize a @StateObject with a parameter coming from an initializer.
To be more specific, this snippet of code works fine:
struct MyView: View {
@StateObject var myObject = MyObject(id: 1)
}
But this does not:
struct MyView: View {
@StateObject var myObject: MyObject
init(id: Int) {
self.myObject = MyObject(id: id)
}
}
From what I understand the role of @StateObject is to make the view the owner of the object.
The current workaround I use is to pass the already initialized MyObject instance like this:
struct MyView: View {
@ObservedObject var myObject: MyObject
init(myObject: MyObject) {
self.myObject = myObject
}
}
But now, as far as I understand, the view that created the object owns it, while this view does not.
Thanks.
| Here is a demo of solution. Tested with Xcode 12+.
class MyObject: ObservableObject {
@Published var id: Int
init(id: Int) {
self.id = id
}
}
struct MyView: View {
@StateObject private var object: MyObject
init(id: Int = 1) {
_object = StateObject(wrappedValue: MyObject(id: id))
}
var body: some View {
Text("Test: \(object.id)")
}
}
From Apple (for all those like @user832):
| Swift | 62,635,914 | 171 |
Before iOS 13, presented view controllers used to cover the entire screen. And, when dismissed, the parent view controller viewDidAppear function were executed.
Now iOS 13 will present view controllers as a sheet as default, which means the card will partially cover the underlying view controller, which means that viewDidAppear will not be called, because the parent view controller has never actually disappeared.
Is there a way to detect that the presented view controller sheet was dismissed? Some other function I can override in the parent view controller rather than using some sort of delegate?
|
Is there a way to detect that the presented view controller sheet was dismissed?
Yes.
Some other function I can override in the parent view controller rather than using some sort of delegate?
No. "Some sort of delegate" is how you do it. Make yourself the presentation controller's delegate and override presentationControllerDidDismiss(_:).
https://developer.apple.com/documentation/uikit/uiadaptivepresentationcontrollerdelegate/3229889-presentationcontrollerdiddismiss
The lack of a general runtime-generated event informing you that a presented view controller, whether fullscreen or not, has been dismissed, is indeed troublesome; but it's not a new issue, because there have always been non-fullscreen presented view controllers. It's just that now (in iOS 13) there are more of them! I devote a separate question-and-answer to this topic elsewhere: Unified UIViewController "became frontmost" detection?.
| Swift | 56,568,967 | 171 |
I want to convert a string to Base64. I found answers in several places, but it does not work anymore in Swift. I am using Xcode 6.2. I believe the answer might be work in previous Xcode versions and not Xcode 6.2.
Could someone please guide me to do this in Xcode 6.2?
The answer I found was this, but it does not work in my version of Xcode:
var str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
// UTF 8 str from original
// NSData! type returned (optional)
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
// Base64 encode UTF 8 string
// fromRaw(0) is equivalent to objc 'base64EncodedStringWithOptions:0'
// Notice the unwrapping given the NSData! optional
// NSString! returned (optional)
let base64Encoded = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println("Encoded: \(base64Encoded)")
// Base64 Decode (go back the other way)
// Notice the unwrapping given the NSString! optional
// NSData returned
let data = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions.fromRaw(0)!)
// Convert back to a string
let base64Decoded = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Decoded: \(base64Decoded)")
ref: http://iosdevelopertips.com/swift-code/base64-encode-decode-swift.html
| Swift
import Foundation
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}
| Swift | 29,365,145 | 171 |
I'm unwrapping two values from a dictionary and before using them I have to cast them and test for the right type. This is what I came up with:
var latitude : AnyObject! = imageDictionary["latitude"]
var longitude : AnyObject! = imageDictionary["longitude"]
if let latitudeDouble = latitude as? Double {
if let longitudeDouble = longitude as? Double {
// do stuff here
}
}
But I would like to pack the two if let queries into one. So that it would something like that:
if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {
// do stuff here
}
That syntax is not working, so I was wondering if there was a beautiful way to do that.
| Update for Swift 3:
The following will work in Swift 3:
if let latitudeDouble = latitude as? Double, let longitudeDouble = longitude as? Double {
// latitudeDouble and longitudeDouble are non-optional in here
}
Just be sure to remember that if one of the attempted optional bindings fail, the code inside the if-let block won't be executed.
Note: the clauses don't all have to be 'let' clauses, you can have any series of boolean checks separated by commas.
For example:
if let latitudeDouble = latitude as? Double, importantThing == true {
// latitudeDouble is non-optional in here and importantThing is true
}
Swift 1.2:
Apple may have read your question, because your hoped-for code compiles properly in Swift 1.2 (in beta today):
if let latitudeDouble = latitude as? Double, longitudeDouble = longitude as? Double {
// do stuff here
}
Swift 1.1 and earlier:
Here's the good news - you can totally do this. A switch statement on a tuple of your two values can use pattern-matching to cast both of them to Double at the same time:
var latitude: Any! = imageDictionary["latitude"]
var longitude: Any! = imageDictionary["longitude"]
switch (latitude, longitude) {
case let (lat as Double, long as Double):
println("lat: \(lat), long: \(long)")
default:
println("Couldn't understand latitude or longitude as Double")
}
Update: This version of the code now works properly.
| Swift | 24,592,004 | 171 |
I'm implementing socket.io in my swift ios app.
Currently on several panels I'm listening to the server and wait for incoming messages. I'm doing so by calling the getChatMessage function in each panel:
func getChatMessage(){
SocketIOManager.sharedInstance.getChatMessage { (messageInfo) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//do sth depending on which panel user is
})
}
}
However I noticed it's a wrong approach and I need to change it - now I want to start listening for incoming messages only once and when any message comes - pass this message to any panel that listens to it.
So I want to pass the incoming message through the NSNotificationCenter. So far I was able to pass the information that something happened, but not pass the data itself. I was doing that by:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.showSpinningWheel(_:)), name: showSpinner, object: nil)
then I had a function called:
func showSpinningWheel(notification: NSNotification) {
}
and any time I wanted to call it I was doing:
NSNotificationCenter.defaultCenter().postNotificationName(hideSpinner, object: self)
So how can I pass the object messageInfo and include it in the function that gets called?
| Swift 2.0
Pass info using userInfo which is an optional Dictionary of type [NSObject : AnyObject]?
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
// For swift 4.0 and above put @objc attribute in front of function Definition
func showSpinningWheel(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
Swift 3.0, 4.0, 5.0 version and above
The userInfo now takes [AnyHashable: Any]? as an argument, which we provide as a dictionary literal in Swift
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
// For swift 4.0 and above put @objc attribute in front of function Definition
func showSpinningWheel(_ notification: NSNotification) {
if let image = notification.userInfo?["image"] as? UIImage {
// do something with your image
}
}
NOTE: Notification βnamesβ are no longer strings, but are of type Notification.Name, hence why we are using NSNotification.Name(rawValue: "notificationName") and we can extend Notification.Name with our own custom notifications.
extension Notification.Name {
static let myNotification = Notification.Name("myNotification")
}
// and post notification like this
NotificationCenter.default.post(name: .myNotification, object: nil)
| Swift | 36,910,965 | 170 |
This is my case:
let passwordSecureTextField = app.secureTextFields["password"]
passwordSecureTextField.tap()
passwordSecureTextField.typeText("wrong_password") //here is an error
UI Testing Failure - Neither element nor any descendant has keyboard focus. Element:
What is wrong? This is working nice for normal textFields, but problem arise only with secureTextFields. Any workarounds?
| This issue caused me a world of pain, but I've managed to figure out a proper solution. In the Simulator, make sure I/O -> Keyboard -> Connect hardware keyboard is off.
| Swift | 32,184,837 | 170 |
What is wrong with my code for getting the filenames in the document folder?
func listFilesFromDocumentsFolder() -> [NSString]?{
var theError = NSErrorPointer()
let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if dirs != nil {
let dir = dirs![0] as NSString
let fileList = NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir, error: theError) as [NSString]
return fileList
}else{
return nil
}
}
I thought I read the documents correctly and I am very sure about what is in the documents folder, but "fileList" does not show anything? "dir" shows the path to the folder.
| Swift 5
do {
// Get the document directory url
let documentDirectory = try FileManager.default.url(
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
print("documentDirectory", documentDirectory.path)
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(
at: documentDirectory,
includingPropertiesForKeys: nil
)
print("directoryContents:", directoryContents.map { $0.localizedName ?? $0.lastPathComponent })
for url in directoryContents {
print(url.localizedName ?? url.lastPathComponent)
}
// if you would like to hide the file extension
for var url in directoryContents {
url.hasHiddenExtension = true
}
for url in directoryContents {
print(url.localizedName ?? url.lastPathComponent)
}
// if you want to get all mp3 files located at the documents directory:
let mp3s = directoryContents.filter(\.isMP3).map { $0.localizedName ?? $0.lastPathComponent }
print("mp3s:", mp3s)
} catch {
print(error)
}
You would need to add those extensions to your project
extension URL {
var typeIdentifier: String? { (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier }
var isMP3: Bool { typeIdentifier == "public.mp3" }
var localizedName: String? { (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName }
var hasHiddenExtension: Bool {
get { (try? resourceValues(forKeys: [.hasHiddenExtensionKey]))?.hasHiddenExtension == true }
set {
var resourceValues = URLResourceValues()
resourceValues.hasHiddenExtension = newValue
try? setResourceValues(resourceValues)
}
}
}
| Swift | 27,721,418 | 170 |
I have a generic function that calls a web service and serialize the JSON response back to an object.
class func invokeService<T>(service: String, withParams params: Dictionary<String, String>, returningClass: AnyClass, completionHandler handler: ((T) -> ())) {
/* Construct the URL, call the service and parse the response */
}
What I'm trying to accomplish is is the equivalent of this Java code
public <T> T invokeService(final String serviceURLSuffix, final Map<String, String> params,
final Class<T> classTypeToReturn) {
}
Is my method signature for what I'm trying to accomplish correct?
More specifically, is specifying AnyClass as a parameter type the
right thing to do?
When calling the method, I'm passing MyObject.self as the returningClass value, but I get a compilation error "Cannot convert the expression's type '()' to type 'String'"
CastDAO.invokeService("test", withParams: ["test" : "test"], returningClass: CityInfo.self) { cityInfo in /*...*/
}
Edit:
I tried using object_getClass, as mentioned by holex, but now I get:
error: "Type 'CityInfo.Type' does not conform to protocol 'AnyObject'"
What need to be done to conform to the protocol?
class CityInfo : NSObject {
var cityName: String?
var regionCode: String?
var regionName: String?
}
| You are approaching it in the wrong way: in Swift, unlike Objective-C, classes have specific types and even have an inheritance hierarchy (that is, if class B inherits from A, then B.Type also inherits from A.Type):
class A {}
class B: A {}
class C {}
// B inherits from A
let object: A = B()
// B.Type also inherits from A.Type
let type: A.Type = B.self
// Error: 'C' is not a subtype of 'A'
let type2: A.Type = C.self
That's why you shouldn't use AnyClass, unless you really want to allow any class. In this case the right type would be T.Type, because it expresses the link between the returningClass parameter and the parameter of the closure.
In fact, using it instead of AnyClass allows the compiler to correctly infer the types in the method call:
class func invokeService<T>(service: String, withParams params: Dictionary<String, String>, returningClass: T.Type, completionHandler handler: ((T) -> ())) {
// The compiler correctly infers that T is the class of the instances of returningClass
handler(returningClass())
}
Now there's the problem of constructing an instance of T to pass to handler: if you try and run the code right now the compiler will complain that T is not constructible with (). And rightfully so: T has to be explicitly constrained to require that it implements a specific initializer.
This can be done with a protocol like the following one:
protocol Initable {
init()
}
class CityInfo : NSObject, Initable {
var cityName: String?
var regionCode: String?
var regionName: String?
// Nothing to change here, CityInfo already implements init()
}
Then you only have to change the generic constraints of invokeService from <T> to <T: Initable>.
Tip
If you get strange errors like "Cannot convert the expression's type '()' to type 'String'", it is often useful to move every argument of the method call to its own variable. It helps narrowing down the code that is causing the error and uncovering type inference issues:
let service = "test"
let params = ["test" : "test"]
let returningClass = CityInfo.self
CastDAO.invokeService(service, withParams: params, returningClass: returningClass) { cityInfo in /*...*/
}
Now there are two possibilities: the error moves to one of the variables (which means that the wrong part is there) or you get a cryptic message like "Cannot convert the expression's type () to type ($T6) -> ($T6) -> $T5".
The cause of the latter error is that the compiler is not able to infer the types of what you wrote. In this case the problem is that T is only used in the parameter of the closure and the closure you passed doesn't indicate any particular type so the compiler doesn't know what type to infer. By changing the type of returningClass to include T you give the compiler a way to determine the generic parameter.
| Swift | 24,308,975 | 170 |
How to check if a file exists in the Documents directory in Swift?
I am using [ .writeFilePath ] method to save an image into the Documents directory and I want to load it every time the app is launched. But I have a default image if there is no saved image.
But I just cant get my head around how to use the [ func fileExistsAtPath(_:) ] function. Could someone give an example of using the function with a path argument passed into it.
I believe I don't need to paste any code in there as this is a generic question. Any help will be much appreciated.
| Swift 4.x version
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
if let pathComponent = url.appendingPathComponent("nameOfFileHere") {
let filePath = pathComponent.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
} else {
print("FILE PATH NOT AVAILABLE")
}
Swift 3.x version
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: path)
let filePath = url.appendingPathComponent("nameOfFileHere").path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
Swift 2.x version, need to use URLByAppendingPathComponent
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.URLByAppendingPathComponent("nameOfFileHere").path!
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
| Swift | 24,181,699 | 170 |
I am making a CheckList application with a UITableView. I was wondering how to add a swipe to delete a UITableViewCell.
This is my ViewController.swift:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView!
var textField: UITextField!
var tableViewData:Array<String> = []
// Define Colors
let lightColor: UIColor = UIColor(red: 0.996, green: 0.467, blue: 0.224, alpha: 1)
let medColor: UIColor = UIColor(red: 0.973, green: 0.388, blue: 0.173, alpha: 1)
let darkColor: UIColor = UIColor(red: 0.800, green: 0.263, blue: 0.106, alpha: 1)
let greenColor: UIColor = UIColor(red: 0.251, green: 0.831, blue: 0.494, alpha: 1)
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
override func viewDidLoad() {
super.viewDidLoad()
//Set up table view
self.tableView = UITableView(frame: CGRectMake(0, 100, self.view.bounds.size.width, self.view.bounds.size.height-100), style: UITableViewStyle.Plain)
self.tableView.registerClass(MyTableViewCell.self, forCellReuseIdentifier: "myCell")
self.tableView.backgroundColor = darkColor
//self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
//Set up text field
self.textField = UITextField(frame: CGRectMake(0, 0, self.view.bounds.size.width, 100))
self.textField.backgroundColor = lightColor
self.textField.font = UIFont(name: "AvenirNext-Bold", size: 26)
self.textField.delegate = self
self.view.addSubview(self.textField)
}
//Table View Delegate
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return tableViewData.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var myNewCell: MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as MyTableViewCell
myNewCell.text = self.tableViewData[indexPath.row]
return myNewCell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let mySelectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)
//Colors
mySelectedCell.detailTextLabel.textColor = UIColor.whiteColor()
mySelectedCell.tintColor = UIColor.whiteColor()
//Setup Details / Date
let myDate:NSDate = NSDate()
var myDateFormatter:NSDateFormatter = NSDateFormatter()
myDateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
mySelectedCell.detailTextLabel.text = myDateFormatter.stringFromDate(myDate)
mySelectedCell.accessoryType = UITableViewCellAccessoryType.Checkmark
mySelectedCell.backgroundColor = greenColor
}
override func prefersStatusBarHidden() -> Bool {
return true
}
//Text Field Delegate
func textFieldShouldReturn(textField: UITextField!) -> Bool {
tableViewData.append(textField.text)
textField.text = ""
self.tableView.reloadData()
textField.resignFirstResponder()
return true
}
}
And this is MyTableViewCell.swift:
import UIKit
class MyTableViewCell: UITableViewCell {
let medColor: UIColor = UIColor(red: 0.973, green: 0.388, blue: 0.173, alpha: 1)
init(style: UITableViewCellStyle, reuseIdentifier: String) {
super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
self.textColor = UIColor.whiteColor()
self.backgroundColor = medColor
self.selectionStyle = UITableViewCellSelectionStyle.None
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
I am using iOS8 as deployment target (not sure of the difference it will make).
| Add these two functions:
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
// handle delete (by removing the data from your array and updating the tableview)
}
}
Swift 3.0:
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCellEditingStyle.delete) {
// handle delete (by removing the data from your array and updating the tableview)
}
}
Swift 4.2
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
// handle delete (by removing the data from your array and updating the tableview)
}
}
| Swift | 24,103,069 | 169 |
I'm currently using Xcode 11 Beta 5. Within my application, it runs fine on iOS 12 and under. However, on iOS 13 it looks like it's using the UIScene by default. This is causing my app to not do anything.
When the app launches on fresh install, there is a terms and conditions the user must accept. After agreeing they go to a loading screen which then directs them to the main view. In the screenshot I posted, the view behind the current one in foreground is the splash loading screen.
We will look into adding multiple views scene support throughout the application soon, but right now we have higher priority stuff we need to work on.
"Support multiple windows" is already disabled in the General settings of the app's target. Also I have Enable Multiple Windows set to NO in the info.plist file.
So far nothing has really worked. Basically I want to opt out/disable multiple windows and UIScene/SwiftUI to restore the original behaviour in iOS 10-12. Is this possible in iOS 13 or we have to update it?
Update:
Here is a screenshot of the view debug hierarchy. Left side is iOS 12, right side is on iOS 13. Without adding anything to the Info.plist nor any scene delegate classes or methods, why is it different? Pretty much just ran it in its existing production ready code on Xcode 11.
| While you should embrace using scenes when your app is run under iOS 13 and later, you can fully opt out while you still support iOS 12 or earlier.
Completely remove the βApplication Scene Manifestβ entry from Info.plist.
If there is a scene delegate class, remove it.
If there are any scene related methods in your app delegate, remove those methods.
If missing, add the property var window: UIWindow? to your app delegate.
Your app should now only use the app delegate and under iOS 13 it should have the same life cycle as iOS 12.
Note: None of this is specific to Swift or SwiftUI.
| Swift | 57,467,003 | 168 |
I want to sort a dictionary in Swift. I have a dictionary like:
"A" => Array[]
"Z" => Array[]
"D" => Array[]
etc. I want it to be like
"A" => Array[]
"D" => Array[]
"Z" => Array[]
etc.
I have tried many solutions on SO but no one worked for me. I am using XCode6 Beta 5 and on it some are giving compiler error and some solutions are giving exceptions. So anyone who can post the working copy of dictionary sorting.
| let dictionary = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]
let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]
EDIT:
The sorted array from the above code contains keys only, while values have to be retrieved from the original dictionary. However, 'Dictionary' is also a 'CollectionType' of (key, value) pairs and we can use the global 'sorted' function to get a sorted array containg both keys and values, like this:
let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
print(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]
EDIT2: The monthly changing Swift syntax currently prefers
let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]
The global sorted is deprecated.
| Swift | 25,377,177 | 168 |
What is the purpose of using IBOutlets and IBActions in Xcode and Interface Builder?
Does it make any difference if I don't use IBOutlets and IBActions?
Swift:
@IBOutlet weak var textField: UITextField!
@IBAction func buttonPressed(_ sender: Any) { /* ... */ }
Objective-C:
@property (nonatomic, weak) IBOutlet UITextField *textField;
- (IBAction)buttonPressed:(id)sender { /* ... */ }
| IBAction and IBOutlet are macros defined to denote variables and methods that can be referred to in Interface Builder.
IBAction resolves to void and IBOutlet resolves to nothing, but they signify to Xcode and Interface builder that these variables and methods can be used in Interface builder to link UI elements to your code.
If you're not going to be using Interface Builder at all, then you don't need them in your code, but if you are going to use it, then you need to specify IBAction for methods that will be used in IB and IBOutlet for objects that will be used in IB.
| Swift | 1,643,007 | 168 |
How to remove the left and right Padding of a List in SwiftUI?
Every List i create has borders to the leading and trailing of a cell.
What modifier should I add to remove this?
| It looks like .listRowInsets doesn't work for rows in a List that is initialised with content.
So this doesn't work:
List(items) { item in
ItemRow(item: item)
.listRowInsets(EdgeInsets())
}
But this does:
List {
ForEach(items) { item in
ItemRow(item: item)
.listRowInsets(EdgeInsets())
}
}
| Swift | 56,614,080 | 167 |
openURL has been deprecated in Swift 3.
Can anyone provide some examples of how the replacement openURL:options:completionHandler: works when trying to open a url?
| All you need is:
guard let url = URL(string: "http://www.google.com") else {
return //be safe
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
| Swift | 39,546,856 | 167 |
How can I do something like this? Take the first n elements from an array:
newNumbers = numbers[0..n]
Currently getting the following error:
error: could not find an overload for 'subscript' that accepts the supplied arguments
EDIT:
Here is the function that I'm working in.
func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
var newNumbers = numbers[0...position]
return newNumbers
}
| This works for me:
var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]
Your issue could be with how you're declaring your array to begin with.
EDIT:
To fix your function, you have to cast your Slice to an array:
func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
var newNumbers = Array(numbers[0..<position])
return newNumbers
}
// test
aFunction([1, 2, 3], 2) // returns [1, 2]
| Swift | 24,034,398 | 167 |
Rather than creating two UIImageViews, it seems logical to simply change the image of one view. If I do that, is there anyway of having a fade/cross dissolve between the two images rather than an instant switch?
| It can be much simpler using the new block-based, UIKit animation methods.
Suppose the following code is in the view controller, and the UIImageView you want to cross-dissolve is a subview of self.view addressable via the property self.imageView Then all you need is:
UIImage * toImage = [UIImage imageNamed:@"myname.png"];
[UIView transitionWithView:self.imageView
duration:5.0f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.imageView.image = toImage;
} completion:nil]
Done.
And to do it in Swift, it's like so:
let toImage = UIImage(named:"myname.png")
UIView.transitionWithView(self.imageView,
duration:5,
options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { self.imageView.image = toImage }, completion: nil)
Swift 3, 4 & 5
let toImage = UIImage(named:"myname.png")
UIView.transition(with: self.imageView,
duration: 0.3,
options: .transitionCrossDissolve,
animations: { self.imageView.image = toImage },
completion: nil)
| Swift | 7,638,831 | 167 |
I am doing a login page. I have UITextField for password.
Obviously, I do not want the password to be seen; instead, I want circles to show when typing.
How do you set the field for this to happen?
| Please set your UItextField property secure..
Try this..
textFieldSecure.secureTextEntry = true
textFieldSecure is your UITextField...
For newer Swift version, it is textFieldSecure.isSecureTextEntry = true
| Swift | 6,578,824 | 167 |
When I set firstThing to default nil this will work, without the default value of nil I get a error that there is a missing parameter when calling the function.
By typing Int? I thought it made it optional with a default value of nil, am I right? And if so, why doesn't it work without the = nil?
func test(firstThing: Int? = nil) {
if firstThing != nil {
print(firstThing!)
}
print("done")
}
test()
| Optionals and default parameters are two different things.
An Optional is a variable that can be nil, that's it.
Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)
If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil. If your function looks like this func test(param: Int?), you can't call it like this test(). Even though the parameter is optional, it doesn't have a default value.
You can also combine the two and have a parameter that takes an optional where nil is the default value, like this: func test(param: Int? = nil).
| Swift | 37,305,951 | 166 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.