I’m setting up a local development environment for a WordPress project using Docker Compose, including WordPress, MySQL, and Adminer containers. Here’s my docker-compose.yml file:
version: '3.8'
services:
wordpress:
image: wordpress:6
container_name: wp_dev
environment:
WORDPRESS_DB_HOST: ${MYSQL_HOST}
WORDPRESS_DB_NAME: ${MYSQL_DATABASE}
WORDPRESS_DB_USER: ${MYSQL_USER}
WORDPRESS_DB_PASSWORD: ${MYSQL_PASSWORD}
ports:
- "8008:80"
volumes:
- ./wp-data:/var/www/html
db:
image: mysql:5
container_name: mysql_dev
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
ports:
- "3305:3306"
volumes:
- db_data_dev:/var/lib/mysql
adminer:
image: adminer:latest
container_name: adminer_dev
ports:
- "8080:8080"
volumes:
db_data_dev:
And my corresponding .env file:
MYSQL_HOST=db:3305
MYSQL_DATABASE=wordpress
MYSQL_ROOT_PASSWORD=root
MYSQL_USER=user
MYSQL_PASSWORD=user_pw
However, I’m encountering a connection error between WordPress and MySQL (see screenshot).
Interestingly, when I modify all the environment variables to use the value “wordpress” and remove any port from the MYSQL_HOST variable, the connection works perfectly. Here’s the modified .env:
MYSQL_HOST=db
MYSQL_DATABASE=wordpress
MYSQL_ROOT_PASSWORD=wordpress
MYSQL_USER=wordpress
MYSQL_PASSWORD=wordpress
Can anyone explain why the connection fails when I use different environment variable values and specify a port? Is there something wrong with my setup or configuration?
Any help or insights would be greatly appreciated!
Thank you in advance!
Update:
Thanks to @Dean Ayalon I have understood the problem with the port.
Now my .env file looks like this:
MYSQL_HOST=db # alternativ db:3306
MYSQL_DATABASE=wordpress
MYSQL_ROOT_PASSWORD=root
MYSQL_USER=user
MYSQL_PASSWORD=user_pw
I am still getting the error from the screenshot in this case.
Because the container uses port 3306, not 3305
Port 3305 is only the host machine’s port that is mapped to the container port 3306. Still to access the container’s service, you need to reach container port 3306, that’s where it listens
If nothing is accessing your db externally, and it’s only used by other container services, you don’t need to map those ports at all
3