I'm trying to use docker-compose to create dynamic and fast development environment and I want to use nginx to route all services. This is my configuration:
docker-compose.yml
version: '3.1'
services:
nginx:
image: nginx
ports:
- 80:80
volumes:
- ./nginx:/etc/nginx/conf.d
wordpress:
image: wordpress
restart: always
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_USER: exampleuser
WORDPRESS_DB_PASSWORD: examplepass
WORDPRESS_DB_NAME: exampledb
volumes:
- ./wordpress:/var/www/html
db:
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: exampledb
MYSQL_USER: exampleuser
MYSQL_PASSWORD: examplepass
MYSQL_RANDOM_ROOT_PASSWORD: '1'
volumes:
- ./db:/var/lib/mysql
nginx conf.d
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://wordpress:80/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
}
But it doesn't work, it is always trying to move from http://localhost to http://localhost:8080
What should I do?
Here are the main issues to address in your sample code:
Both nginx and wordpress Docker images listen on port 80 by default. So you should map wordpress to a different one. For example 8080
All the images will not be able to see each other unless you set up a network for them.
Update nginx configuration to remove the port for wordpress. Being in the same network they see each other usin their host names only (so their image name)
Had to change the way you declare the volumes used by wordpress and mysql images
So this is what I suggest to have:
docker-compose
version: '3.1'
services:
nginx:
image: nginx
ports:
- 80:80
volumes:
- ./nginx:/etc/nginx/conf.d
networks:
- backend
wordpress:
image: wordpress
ports:
- 8080:80
restart: always
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_USER: exampleuser
WORDPRESS_DB_PASSWORD: examplepass
WORDPRESS_DB_NAME: exampledb
volumes:
- wordpress:/var/www/html
networks:
- backend
db:
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: exampledb
MYSQL_USER: exampleuser
MYSQL_PASSWORD: examplepass
MYSQL_RANDOM_ROOT_PASSWORD: '1'
volumes:
- db:/var/lib/mysql
networks:
- backend
volumes:
wordpress:
db:
networks:
backend:
driver: bridge
nginx.conf
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://wordpress/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
}
You can check more details about networking in Docker Compose in the documentation.