Can’t connect to database server
docker-compose:
version: '3.7'
services:
nginx:
container_name: app_nginx
image: nginx:latest
volumes:
- ./:/var/www
- ./docker/nginx/conf.d:/etc/nginx/conf.d
ports:
- "8876:80"
depends_on:
- app
app:
container_name: app
build:
context: .
dockerfile: docker/app/Dockerfile
volumes:
- ./:/var/www
depends_on:
- db
db:
container_name: app_db
image: mysql:8.0
restart: always
volumes:
- ./tmp/db:/var/lib/mysql
environment:
MYSQL_DATABASE: zastroy
MYSQL_ROOT_PASSWORD: root
ports:
- "8101:3306"
command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
I tried changing the host to app_db and just db , but then it doesn’t find the address at all
2
Answers
make sure you have created a docker network first so that nginx and mysql can communicate
docker network create -d bridge app_network
when it has been created, add it to docker compose with the same network on mysql and nginx
When docker compose runs containers, it creates a docker bridge network which it connects the containers to. On the bridge network, the containers can talk to each other using the service names as host names.
That means that your other containers can reach the database using the hostname
db
and port 3306.If you want to be able to reach any of the containers from outside the bridge network, you map a port on the host to a container port. You’ve mapped the database container port 3306 to the host port 8101.
That means that your other containers can reach the database on
db:3306
but if you want to reach it from the host machine, you have to uselocalhost:8101
.In your screenshot, you’re using
localhost:3306
which won’t work. You need to use port 8101 from the host.There’s more information here.