How to run a server (mysql or redis) in docker and run a cli client in it to connect itself.
docker run -it --rm \
--name mysql-container \
-e MYSQL_ROOT_PASSWORD=mypassword \
-p 3307:3306 \
mysql \
mysql -u root -h localhost -P 3306 -p
gives error:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
docker run -it --rm \
--name my-redis \
redis \
redis-cli -h localhost
gives error
Could not connect to Redis at 127.0.0.1:6379: Connection refused
I'm new to docker. I'm assuming it should run the server and then my client commands. But its not working.
What am I missing?
Actually, you need to wait for the mysql-server
and redis-server
in the container
to finish booting before executing the login command. Boot time depends on many factors. To be safe, I think you should add sleep
between commands.
You can try this:
docker run -d --rm \
--name mysql-container \
-e MYSQL_ROOT_PASSWORD=mypassword \
-p 3307:3306 \
mysql && sleep 5 && \
docker exec -it mysql-container \
bash -c "mysql -u root -h localhost -P 3306 -p"
docker run -d --rm \
--name my-redis \
redis && sleep 5 && \
docker exec -it my-redis \
redis-cli -h localhost