NGINX & Consul-Template in Docker - nginx

I'm having trouble with consistent service discovery using EC2, AWS, Docker, Consul-Template, Consul, and NGINX.
I have multiple services, each running on it's own EC2 instance. On these instances I run the following containers (in this order):
cAdvisor (monitoring)
node-exporter (monitoring)
Consul (running in agent mode)
Registrator
My service
Custom container running both nginx and consul-template
The custom container has the following Dockerfile:
FROM nginx:1.9
#Install Curl
RUN apt-get update -qq && apt-get -y install curl
#Install Consul Template
RUN curl -L https://github.com/hashicorp/consul-template/releases/download/v0.10.0/consul-template_0.10.0_linux_amd64.tar.gz | tar -C /usr/local/bin --strip-components 1 -zxf -
#Setup Consul Template Files
RUN mkdir /etc/consul-templates
COPY ./app.conf.tmpl /etc/consul-templates/app.conf
# Remove all other conf files from nginx
RUN rm /etc/nginx/conf.d/*
#Default Variables
ENV CONSUL consul:8500
CMD /usr/sbin/nginx -c /etc/nginx/nginx.conf && consul-template -consul=$CONSUL -template "/etc/consul-templates/app.conf:/etc/nginx/conf.d/app.conf:/usr/sbin/nginx -s reload"
The app.conf file looks like this:
{{range services}}
upstream {{.Name}} {
least_conn;{{range service .Name}}
server {{.Address}}:{{.Port}};{{end}}
}
{{end}}
server {
listen 80 default_server;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location / {
proxy_pass http://cart/cart/;
}
location /cart {
proxy_pass http://cart/cart;
}
{{range services}}
location /api/{{.Name}} {
proxy_read_timeout 180;
proxy_pass http://{{.Name}}/{{.Name}};
}
{{end}}
}
Everything seems to start up perfectly ok, but at some point (which I'm yet to identify) after start up, consul-template seems to return that there are no available servers for a particular service. This means that the upstream section for that service contains no servers, and I end up with this in the logs:
2015/12/04 07:09:34 [emerg] 77#77: no servers are inside upstream in /etc/nginx/conf.d/app.conf:336
nginx: [emerg] no servers are inside upstream in /etc/nginx/conf.d/app.conf:336
2015/12/04 07:09:34 [ERR] (runner) error running command: exit status 1
Consul Template returned errors:
1 error(s) occurred:
* exit status 1
2015/12/04 07:09:34 [DEBUG] (logging) setting up logging
2015/12/04 07:09:34 [DEBUG] (logging) config:
{
"name": "consul-template",
"level": "WARN",
"syslog": false,
"syslog_facility": "LOCAL0"
}
2015/12/04 07:09:34 [emerg] 7#7: no servers are inside upstream in /etc/nginx/conf.d/app.conf:336
nginx: [emerg] no servers are inside upstream in /etc/nginx/conf.d/app.conf:336
After this, NGINX will no longer accept requests.
I'm sure I'm missing something obvious, but I've tied myself in mental knots about the sequence of events etc. What I think might be happening is that NGINX crashes, but because consul-template is still running, the Docker container doesn't restart. I don't actually care if the container itself restarts, or if just NGINX restarts.
Can someone help?

Consul Template will exit once the script it runs after writing returns a non-zero exit code. See here for the documentation.
The documentation suggests to put a || true just after the restart (or reload) command. This will keep Consul Template running independent of the exit code.
You could consider wrapping the restart in its own shell script that first tests the configuration (with nginx -t) before triggering a reload. You could even move the initial start of nginx to this script as it only makes sense to start nginx once the first (valid) configuration has been written?!

Related

why I am getting Read only file system error from Nginx?

Dear K8S community Team,
I am getting this error message from nginx when I deploy my application pod. My application an angular6 app is hosted inside an nginx server, which is deployed as a docker container inside EKS.
I have my application configured as a “read-only container filesystem”, but I am using “ephemeral mounted” volume of type “emptyDir” in combination with a read-only filesystem.
So I am not sure the reason of this following error:
2019/04/02 14:11:29 [emerg] 1#1: mkdir()
"/var/cache/nginx/client_temp" failed (30: Read-only file system)
nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (30:
Read-only file system)
My deployment.yaml is:
...
spec:
volumes:
- name: tmp-volume
emptyDir: {}
# Pod Security Context
securityContext:
fsGroup: 2000
containers:
- name: {{ .Chart.Name }}
volumeMounts:
- mountPath: /tmp
name: tmp-volume
image: "{{ .Values.image.name }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
securityContext:
capabilities:
add:
- NET_BIND_SERVICE
drop:
- ALL
securityContext:
readOnlyRootFilesystem: true
ports:
- name: http
containerPort: 80
protocol: TCP
...
nginx.conf is:
...
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Turn off the bloody buffering to temp files
proxy_buffering off;
sendfile off;
keepalive_timeout 120;
server_names_hash_bucket_size 128;
# These two should be the same or nginx will start writing
# large request bodies to temp files
client_body_buffer_size 10m;
client_max_body_size 10m;
...
Seems like your nginx is not running as root user.
Since release 1.12.1-r2, nginx daemon is being run as user 1001.
1.12.1-r2
The nginx container has been migrated to a non-root container approach. Previously the container run as root user and the nginx daemon was started as nginx user. From now own, both the container and the nginx daemon run as user 1001. As a consequence, the configuration files are writable by the user running the nginx process.
This is why you are unable to bind on port 80, it's necessary to use port > 1000.
You should use:
ports:
- '80:8080'
- '443:8443'
and edit the nginx.conf so it listens on port 8080:
server {
listen 0.0.0.0:8080;
...
Or run nginx as root:
command: [ "/bin/bash", "-c", "sudo nginx -g 'daemon off;'" ]
As already stated by Crou, the nginx image maintainers switched to a non-root-user-approach.
This has two implications:
Your nginx process might not be able to bind all network sockets.
Your nginx process might not be able to read all file system locations.
You can try to change the ports as described by Crou (nginx.conf and deployment.yaml). Even with the NET_BIND_SERVICE capability added to the container, this does not neccessarily mean that the nginx process gets this capability. You can try to add the capability with
$ sudo setcap 'cap_net_bind+p' $(which nginx)
as a RUN instruction in your Dockerfile.
However it is usually simpler to just change the listening port.
For the filesystem, please note that /var/cache/nginx/ is not mounted as a volume and thus belongs to the RootFS which is mounted as read only. The simplest way to solve this, is to add a second epheremal emptyDir for /var/cache/nginx/ in the volumes section. Please make sure, that the nginx user has the file system permissions to read and write this directory. This is usually already taken care of by the docker image maintainers as long as you stay with the default locations.
I recommend you to not switch back to running nginx as root as this might expose you to security vulnerabilities.

Authorization Issue with Certbot(Standalone)+Nginx+Chef

I use Nginx on my server and want to serve my application on HTTPS using Let's Encrypt certs. I do the following on a fresh server before the application code gets deployed:
Install Nginx
Write the following nginx configuration file to sites-available, for certbot. Then symlink to sites-enabled and restart nginx
server {
listen 80;
server_name foo.bar.com;
allow all;
location ^~ /.well-known/acme-challenge/ {
proxy_pass http://0.0.0.0:22000;
}
}
Then run certbot
certbot certonly -m foo#bar.com --standalone --http-01-port 22000 --preferred-challenges http --cert-name bar.com -d foo.bar.com --agree-tos --non-interactive
All of the above work fine when run manually.
I use Chef to automate the above process. Certbot gets a 404 the first time I deploy. It works on subsequent deployments though.
Keep a note of the following detail:
The phenomenon happens only when I freshly install Nginx and then run my deploy script through Chef and disappears on subsequent deploys.
I use a custom LWRP to run the above steps in Chef expcept nginx installation. Nginx installation is taken care of by chef_nginx. I've pasted the snippet of the LWRP that runs the above steps.
vhost_file = "#{node['certbot']['sites_configuration_path']}/#{node['certbot']['sites_configuration_file']}"
template vhost_file do
cookbook 'certbot'
source 'nginx-letsencrypt.vhost.conf.erb'
owner 'root'
group 'root'
variables(
server_names: new_resource.sans,
certbot_port: node['certbot']['standalone_port'],
mode: node['certbot']['standalone_mode']
)
mode 00644
only_if "test -d #{node['certbot']['sites_configuration_path']}"
end
nginx_site node['certbot']['sites_configuration_file']
Using certbot in standalone mode on port 22000
How do I make things work even on the first deployment ?

Nginx permission denied

I want to deploy my flask service in a server with centOS 7. So I followed this tutorial - https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-centos-7 .
After runnning systemctl start nginx command, I got this error:
nginx: [emerg] bind() to 0.0.0.0:5000 failed (13: Permission denied)
My nginx.conf file:
server {
listen 5000;
server_name _;
location / {
include uwsgi_params;
uwsgi_pass unix:/root/fiproxy/fiproxyproject/fiproxy.sock;
}
}
Note: flask service and wsgi work ok. And I've tried to run nginx with superuser and the error remains.
After search a lot in Internet, I found a solution to my problem.
I ran this command to get all used ports in my machine: semanage port -l.
After that, I filtered the output with: semanage port -l | grep 5000.
I realized that this port 5000 is used by commplex_main_port_t, I searched in speedguide and I found: 5000 tcp,udp **UPnP**.
Conclusion, maybe my problem was bind a standard port.
To add your desired port use this command:
sudo semanage port -a -t http_port_t -p tcp [yourport]
Now run nginx with sudo:
sudo systemctl stop nginx
sudo systemctl start nginx
The Nginx master process needs root permission. Because it needs bind port.
You need start Nginx under root user.
Then you can define the user of child processes in nginx.conf.

How to serve other vhosts next to Gitlab Omnibus server? [Full step-by-step solution]

I installed Gitlab CE on a dedicated Ubuntu 14.04 server edition with Omnibus package.
Now I would want to install three other virtual hosts next to gitlab.
Two are node.js web applications launched by a non-root user running on two distinct ports > 1024, the third is a PHP web application that need a web server to be launched from.
There are:
a private bower registry running on 8081 (node.js)
a private npm registry running on 8082 (node.js)
a private composer registry (PHP)
But Omnibus listen 80 and doesn't seem to use neither Apache2 or Nginx, thus I can't use them to serve my PHP app and reverse-proxy my two other node apps.
What serving mechanics Gitlab Omnibus uses to listen 80 ?
How should I create the three other virtual hosts to be able to provide the following vHosts ?
gitlab.mycompany.com (:80) -- already in use
bower.mycompany.com (:80)
npm.mycompany.com (:80)
packagist.mycompany.com (:80)
About these
But Omnibus listen 80 and doesn't seem to use neither Apache2 or Nginx [, thus ...].
and #stdob comment :
Did omnibus not use nginx as a web server ??? –
Wich I responded
I guess not because nginx package isn't installed in the system ...
In facts
From Gitlab official docs :
By default, omnibus-gitlab installs GitLab with bundled Nginx.
So yes!
Omnibus package actually uses Nginx !
but it was bundled, explaining why it doesn't require to be installed as dependency from the host OS.
Thus YES! Nginx can, and should be used to serve my PHP app and reverse-proxy my two other node apps.
Then now
Omnibus-gitlab allows webserver access through user gitlab-www which resides
in the group with the same name. To allow an external webserver access to
GitLab, external webserver user needs to be added gitlab-www group.
To use another web server like Apache or an existing Nginx installation you will have to do
the following steps:
Disable bundled Nginx by specifying in /etc/gitlab/gitlab.rb
nginx['enable'] = false
# For GitLab CI, use the following:
ci_nginx['enable'] = false
Check the username of the non-bundled web-server user. By default, omnibus-gitlab has no default setting for external webserver user.
You have to specify the external webserver user username in the configuration!
Let's say for example that webserver user is www-data.
In /etc/gitlab/gitlab.rb set
web_server['external_users'] = ['www-data']
This setting is an array so you can specify more than one user to be added to gitlab-www group.
Run sudo gitlab-ctl reconfigure for the change to take effect.
Setting the NGINX listen address or addresses
By default NGINX will accept incoming connections on all local IPv4 addresses.
You can change the list of addresses in /etc/gitlab/gitlab.rb.
nginx['listen_addresses'] = ["0.0.0.0", "[::]"] # listen on all IPv4 and IPv6 addresses
For GitLab CI, use the ci_nginx['listen_addresses'] setting.
Setting the NGINX listen port
By default NGINX will listen on the port specified in external_url or
implicitly use the right port (80 for HTTP, 443 for HTTPS). If you are running
GitLab behind a reverse proxy, you may want to override the listen port to
something else. For example, to use port 8080:
nginx['listen_port'] = 8080
Similarly, for GitLab CI:
ci_nginx['listen_port'] = 8081
Supporting proxied SSL
By default NGINX will auto-detect whether to use SSL if external_url
contains https://. If you are running GitLab behind a reverse proxy, you
may wish to keep the external_url as an HTTPS address but communicate with
the GitLab NGINX internally over HTTP. To do this, you can disable HTTPS using
the listen_https option:
nginx['listen_https'] = false
Similarly, for GitLab CI:
ci_nginx['listen_https'] = false
Note that you may need to configure your reverse proxy to forward certain
headers (e.g. Host, X-Forwarded-Ssl, X-Forwarded-For, X-Forwarded-Port) to GitLab.
You may see improper redirections or errors (e.g. "422 Unprocessable Entity",
"Can't verify CSRF token authenticity") if you forget this step. For more
information, see:
What's the de facto standard for a Reverse Proxy to tell the backend SSL is used?
https://wiki.apache.org/couchdb/Nginx_As_a_Reverse_Proxy
To go further you can follow the official docs at https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/doc/settings/nginx.md#using-a-non-bundled-web-server
Configuring our gitlab virtual host
Installing Phusion Passenger
We need to install ruby (gitlab run in omnibus with a bundled ruby) globally in the OS
$ sudo apt-get update
$ sudo apt-get install ruby
$ sudo gem install passenger
Recompile nginx with the passenger module
Instead of Apache2 for example, nginx isn't able to be plugged with binary modules on-the-fly. It must be recompiled for each new plugin you want to add.
Phusion passenger developer team worked hard to provide saying, "a bundled nginx version of passenger" : nginx bins compiled with passenger plugin.
So, lets use it:
requirement: we need to open our TCP port 11371 (the APT key port).
$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 561F9B9CAC40B2F7
$ sudo apt-get install apt-transport-https ca-certificates
creating passenger.list
$ sudo nano /etc/apt/sources.list.d/passenger.list
with these lignes
# Ubuntu 14.04
deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main
use the right repo for your ubuntu version. For Ubuntu 15.04 for example:
deb https://oss-binaries.phusionpassenger.com/apt/passenger vivid main
Edit permissions:
$ sudo chown root: /etc/apt/sources.list.d/passenger.list
$ sudo chmod 600 /etc/apt/sources.list.d/passenger.list
Updating package list:
$ sudo apt-get update
Allowing it as unattended-upgrades
$ sudo nano /etc/apt/apt.conf.d/50unattended-upgrades
Find or create this config block on top of the file:
// Automatically upgrade packages from these (origin:archive) pairs
Unattended-Upgrade::Allowed-Origins {
// you may have some instructions here
};
Add the following:
// Automatically upgrade packages from these (origin:archive) pairs
Unattended-Upgrade::Allowed-Origins {
// you may have some instructions here
// To check "Origin:" and "Suite:", you could use e.g.:
// grep "Origin\|Suite" /var/lib/apt/lists/oss-binaries.phusionpassenger.com*
"Phusion:stable";
};
Now (re)install nginx-extra and passenger:
$ sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak_"$(date +%Y-%m-%d_%H:%M)"
$ sudo apt-get install nginx-extras passenger
configure it
Uncomment the passenger_root and passenger_ruby directives in the /etc/nginx/nginx.conf file:
$ sudo nano /etc/nginx/nginx.conf
... to obtain something like:
##
# Phusion Passenger config
##
# Uncomment it if you installed passenger or passenger-enterprise
##
passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /usr/bin/passenger_free_ruby;
create the nginx site configuration (the virtual host conf)
$ nano /etc/nginx/sites-available/gitlab.conf
server {
listen *:80;
server_name gitlab.mycompany.com;
server_tokens off;
root /opt/gitlab/embedded/service/gitlab-rails/public;
client_max_body_size 250m;
access_log /var/log/gitlab/nginx/gitlab_access.log;
error_log /var/log/gitlab/nginx/gitlab_error.log;
# Ensure Passenger uses the bundled Ruby version
passenger_ruby /opt/gitlab/embedded/bin/ruby;
# Correct the $PATH variable to included packaged executables
passenger_env_var PATH "/opt/gitlab/bin:/opt/gitlab/embedded/bin:/usr/local/bin:/usr/bin:/bin";
# Make sure Passenger runs as the correct user and group to
# prevent permission issues
passenger_user git;
passenger_group git;
# Enable Passenger & keep at least one instance running at all times
passenger_enabled on;
passenger_min_instances 1;
error_page 502 /502.html;
}
Now we can enable it:
$ sudo ln -s /etc/nginx/sites-available/gitlab.cong /etc/nginx/sites-enabled/
There is no a2ensite equivalent coming natively with nginx, so we use ln, but if you want, there is a project on github:
nginx_ensite:
nginx_ensite and nginx_dissite for quick virtual host enabling and disabling
This is a shell (Bash) script that replicates for nginx the Debian a2ensite and a2dissite for enabling and disabling sites as virtual hosts in Apache 2.2/2.4.
It' done :-). Finally, restart nginx
$ sudo service nginx restart
With this new configuration, you are able to run other virtual hosts next to gitlab to serve what you want
Just create new configs in /etc/nginx/sites-available.
In my case, I made running and serving this way on the same host :
gitlab.mycompany.com - the awesome git platform written in ruby
ci.mycompany.com - the gitlab continuous integration server written in ruby
npm.mycompany.com - a private npm registry written in node.js
bower.mycompany.com - a private bower registry written in node.js
packagist.mycompany.com - a private packagist for composer registry written in php
For example, to serve npm.mycompany.com :
Create a directory for logs:
$ sudo mkdir -p /var/log/private-npm/nginx/
And fill a new vhost config file:
$ sudo nano /etc/nginx/sites-available/npm.conf
With this config
server {
listen *:80;
server_name npm.mycompany.com
client_max_body_size 5m;
access_log /var/log/private-npm/nginx/npm_access.log;
error_log /var/log/private-npm/nginx/npm_error.log;
location / {
proxy_pass http://localhost:8082;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Then enable it and restart it:
$ sudo ln -s /etc/nginx/sites-available/npm.conf /etc/nginx/sites-enabled/
$ sudo service nginx restart
As I would not like to change the nginx server for gitlab (with some other integrations), the safest way would be below solution.
also as per
Gitlab:Ningx =>Inserting custom settings into the NGINX config
edit the /etc/gitlab/gitlab.rb of your gitlab:
nano /etc/gitlab/gitlab.rb
and sroll to nginx['custom_nginx_config'] and modify as below make sure to uncomment
# Example: include a directory to scan for additional config files
nginx['custom_nginx_config'] = "include /etc/nginx/conf.d/*.conf;"
create the new config dir:
mkdir -p /etc/nginx/conf.d/
nano /etc/nginx/conf.d/new_app.conf
and add content to your new config
# my new app config : /etc/nginx/conf.d/new_app.conf
# set location of new app
upstream new_app {
server localhost:1234; # wherever it might be
}
# set the new app server
server {
listen *:80;
server_name new_app.mycompany.com;
server_tokens off;
access_log /var/log/new_app_access.log;
error_log /var/log/new_app_error.log;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
location / { proxy_pass http://new_app; }
}
and reconfigure gitlab to get the new settings inserted
gitlab-ctl reconfigure
to restart nginx
gitlab-ctl restart nginx
to check nginx error log:
tail -f /var/log/gitlab/nginx/error.log

Docker: Nginx and php5-fpm dockers are not talking

I’d like to make a fully dockerized Drupal install. My first step is to get containers running with Nginx and php5-fpm, both Debian based. I’m on CoreOS alpha channel (using Digital Ocean.)
My Dockerfiles are the following:
Nginx:
FROM debian
MAINTAINER fvhemert
RUN apt-get update && apt-get install -y nginx && echo "\ndaemon off;" >> /etc/nginx/nginx.conf
CMD ["nginx"]
EXPOSE 80
This container build and runs nicely. I see the default Nginx page on my server ip.
Php5-fpm:
FROM debian
MAINTAINER fvhemert
RUN apt-get update && apt-get install -y \
php5-fpm \
&& sed 's/;daemonize = yes/daemonize = no/' -i /etc/php5/fpm/php-fpm.conf
CMD ["php5-fpm"]
EXPOSE 9000
This container also builds with no problems and it keeps running when started.
I start the php5-fpm container first with:
docker run -d --name php5-fpm freek/php5-fpm:1
Ad then I start Nginx,, linked to php5-fpm:
docker run -d -p 80:80 --link php5-fpm:phpserver --name nginx freek/nginx-php:1
The linking seems to work, there is an entry in /etc/hosts with name phpserver. Both dockers run:
core#dockertest ~ $ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
fd1a9ae0f1dd freek/nginx-php:4 "nginx" 38 minutes ago Up 38 minutes 0.0.0.0:80->80/tcp nginx
3bd12b3761b9 freek/php5-fpm:2 "php5-fpm" 38 minutes ago Up 38 minutes 9000/tcp php5-fpm
I have adjusted some of the config files. For the Nginx container I edited /etc/nginx/sites-enabled/default and changed:
server {
#listen 80; ## listen for ipv4; this line is default and implied
#listen [::]:80 default_server ipv6only=on; ## listen for ipv6
root /usr/share/nginx/www;
index index.html index.htm index.php;
(I added the index.php)
And further on:
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
fastcgi_pass phpserver:9000;
# # With php5-fpm:
# fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
In the php5-fpm docker I changed /etc/php5/fpm/php.ini:
cgi.fix_pathinfo=0
php5-fpm runs:
[21-Nov-2014 06:15:29] NOTICE: fpm is running, pid 1
[21-Nov-2014 06:15:29] NOTICE: ready to handle connections
I also changed index.html to index.php, it looks like this (/usr/share/nginx/www/index.php):
<html>
<head>
<title>Welcome to nginx!</title>
</head>
<body bgcolor="white" text="black">
<center><h1>Welcome to nginx!</h1></center>
<?php
phpinfo();
?>
</body>
</html>
I have scanned the 9000 port from the Nginx docker, it appears as closed. Not a good sign of course:
root#fd1a9ae0f1dd:/# nmap -p 9000 phpserver
Starting Nmap 6.00 ( http://nmap.org ) at 2014-11-21 06:49 UTC
Nmap scan report for phpserver (172.17.0.94)
Host is up (0.00022s latency).
PORT STATE SERVICE
9000/tcp closed cslistener
MAC Address: 02:42:AC:11:00:5E (Unknown)
Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds
The Nginx logs:
root#fd1a9ae0f1dd:/# vim /var/log/nginx/error.log
2014/11/20 14:43:46 [error] 13#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 194.171.252.110, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "128.199.60.95"
2014/11/21 06:15:51 [error] 9#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 145.15.244.119, server: localhost, request: "GET / HTTP/1.0", upstream: "fastcgi://172.17.0.94:9000", host: "128.199.60.95"
Yes, that goes wrong and I keep getting a 502 bad gateway error when browsing to my Nginx instance.
My question is: What exactly goes wrong? My guess is that I’m missing some setting in the php config files.
EDIT FOR MORE DETAILS:
This is the result (from inside the php5-fpm container, after apt-get install net-tools):
root#3bd12b3761b9:/# netstat -tapen
Active Internet connections
(servers and established) Proto Recv-Q Send-Q Local Address
Foreign Address State User Inode PID/Program name
From inside the Nginx container:
root#fd1a9ae0f1dd:/# netstat -tapen
Active Internet connections
(servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program
name tcp 0 0 0.0.0.0:80 0.0.0.0:*
LISTEN 0 1875387 -
EDIT2:
Progression!
In the php5-fpm container, in the file:
/etc/php5/fpm/pool.d/www.conf
I changed the listen argument from some socket name to:
listen = 9000
Now when I go to my webpage I get the error:
"No input file specified."
Probably I have trailing / wrong somewhere. I'll look into it more closely!
EDIT3:
So I have rebuild the dockers with the above mentioned alterations and it seems that they are talking. However, my webpage tells me: "file not found."
I'm very sure it has to do with the document that nginx sents to php-fpm but I have no idea how it should look like. I used the defaults when using the socket method which always worked. Now it doesn't work anymore. What should be in /etc/nginx/sites-enabled/default under location ~ .php$ { ?
The reason it doesn't work is, as you have discovered yourself, that nginx only sends the path of the PHP file to PHP-FPM, not the file itself (which would be quite inefficient). The solution is to use a third, data-only VOLUME container to host the files, and then mount it on both docker instances.
FROM debian
VOLUME /var/www
CMD ['true']
Build the above Dockerfile and create an instance (call it for example: storage-www), then run both the nginx and the PHP-FPM containers with the option:
--volumes-from storage-www
That will work if you run both containers on the same physical server.
But you still could use different servers, if you put that data-only container on a networked file-system, such as GlusterFS, which is quite efficient and can be distributed over a large-scale network.
Hope that helps.
Update:
As of 2015, the best way to make persistent links between containers is to use docker-compose.
So, I have tested all settings and none worked between dockers while they did work with the same settings on 1 server (or also in one docker probably). Then I found out that php-fpm is not taking php files from nginx, it is receiving the path, if it can't find the same file in its own container it generates a "file not found". See here for more information: https://code.google.com/p/sna/wiki/NginxWithPHPFPM So that solves the question but not the problem, sadly. This is quite annoying for people that want to do load balancing with multiple php-fpm servers, they'd have to rsync everything or something like that. I hope someday I'll find a better solution. Thanx for the replies.
EDIT: Perhaps I can mount the same volume in both containers and get it to work that way. That won't be a solution when using multiple servers though.
When you are in your container as
root#fd1a9ae0f1dd:/#
, check the ports used with
netstat -tapen | grep ":9000 "
or
netstat -lntpu | grep ":9000 "
or the same commands without the grep

Resources