Hello to all the readers!

Well there is a scenario that we have to run mysql database along with the application. And the container concept says that these two services should be run independently in their own container.

But then there is a need that both the containers can talk to each other. For that containers have to be on the same network.

Let us create a network object.

docker network create todo-app

Next we will create a mysql container.

docker run -d --network todo-app --network-alias mysql -v todo-mysql-data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=secret -e MYSQL_DATABASE=todos mysql:8.0

The volume named “todo-mysql-data” is automatically created. We didn’t create it explicitly. Let’s login to mysql.

docker exec -it f0423bcb66e0 mysql -u root -p

Next we will create a container out of a popular network debug tool image. nicolaka/netshoot contains a lot of useful network tools.

docker run -it --network todo-app nicolaka/netshoot

d0907c828a4b  ~  dig mysql

; <<>> DiG 9.18.13 <<>> mysql
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 52601
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;mysql.                         IN      A

;; ANSWER SECTION:
mysql.                  600     IN      A       172.20.0.2

;; Query time: 3 msec
;; SERVER: 127.0.0.11#53(127.0.0.11) (UDP)
;; WHEN: Thu Jun 22 08:35:24 UTC 2023
;; MSG SIZE  rcvd: 44

We could see that hostname “mysql” that was set as network alias is able to resolve. So we will use app container to connect to this hostname.

docker run -dp 3000:3000 -w /app -v "$(pwd):/app" --network todo-app -e MYSQL_HOST=mysql -e MYSQL_USER=root -e MYSQL_PASSWORD=secret -e MYSQL_DB=todos node:18-alpine sh -c "yarn install && yarn run dev"
Connected!
Connected to mysql db at host mysql

Logs of container shows that it is connected to mysql database.

Similar Posts

Error: GraphComment couldn't be load because your settings are invalid. Please visit your admin panel and go to the GraphComment section and enter a valid website URL/ID.