Reputation: 129
So, I've got a MySQL docker container on which I run a script to write into the database, but when I execute the script, my script throws
mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)
Do I have to start the MySQL service in the Dockerfile?
docker-compose.yml:
version: '3.3'
services:
db:
build: .
restart: always
environment:
MYSQL_ROOT_PASSWORD: test
MYSQL_DATABASE: test
MYSQL_USER: test
MYSQL_PASSWORD: test
volumes:
- ./db_data:/docker-entrypoint-initdb.d
Upvotes: 0
Views: 5698
Reputation: 848
First you need to expose the MySQL port 3306
or any other port you set for the MySQL
and then you can get help from commmand
parameter.
A working sample would be like this:
version: '3.1'
services:
db:
image: mysql
container_name: mysql_test
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: root_password
MYSQL_DATABASE: test
MYSQL_USER: test_user
MYSQL_PASSWORD: test_password
ports:
- 30001:3306
expose:
- 30001
volumes:
- my-db:/var/lib/mysql
networks:
- test
networks:
test:
volumes:
my-db:
driver: local
With this sample code you will be able to connect with localhost:30001
to your database from host machine and mysql_test:3306
from other containers within the same network.
Upvotes: 6
Reputation: 3691
If you're trying to execute script in your host, you need to export port 3306
version: '3.3'
services:
db:
build: .
restart: always
environment:
MYSQL_ROOT_PASSWORD: test
MYSQL_DATABASE: test
MYSQL_USER: test
MYSQL_PASSWORD: test
ports:
- 3306:3306
volumes:
- ./db_data:/docker-entrypoint-initdb.d
If you're trying to execute inside docker (with a docker exec for example), check if container is up with docker ps
Upvotes: 1