How to connect Node.js app to database when they are running in separate Docker containers?

后端 未结 1 363
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 00:41

I have these containers running:

I am able to visit node app at localhost:49160 and database at localhost:7474 as expected.

<
相关标签:
1条回答
  • 2020-12-04 01:07

    I am describing one way of doing it, and there might be other possible ways which I am currently unaware of. Since the links are deprecated now, we can use networks to connect one container to another.

    First of all we create a network with this command:

    docker network create -d bridge --subnet 172.25.0.0/16 isolated_nw

    And then we connect the mysql container by assigning it an IP address from the network we created. And yeah, we specify the network too. This command does the required purpose:

    docker run -itd --rm \
      --network=isolated_nw \
      --ip=172.25.3.3 \
      --name=mysql \
      --volume "$(pwd)/database/:/docker-entrypoint-initdb.d" mysql
    

    Now we have got our mysql container running and connected to the isolated_nw we created. Its time to get our other container connected to the same network and access the mysql container. Adding --network=isolated_nw flag while running a container adds the container to the network. And we shall use this flag while running our other container which requires to access mysql.

    Now it is done! Inside this other container we can access mysql container at the IP address we allocated, i.e, at 172.25.3.3. An implementation of these things can be seen here.

    0 讨论(0)
提交回复
热议问题