简体   繁体   中英

Share IP between containers using docker-compose

I use docker-compose to link containers. The structure looks like this:

version: '3.3'
services:
  db_service:
    ...
  api_service:
    ...
  ...

I know Nginx can access the IP of other containers using the following code:

location /api/ {
    proxy_pass      http://api_service:5000;
}

I would like to extend this question where a concrete example would have been appreciated.

In my situation, I would like to connect to a database located in another container. The IP of the database is given by: $ docker inspect my_db | grep "IPAddress" $ docker inspect my_db | grep "IPAddress" and it is not constant over different runtimes. The code below works currently but I am looking for something more robust which resists a simple reboot and is ideally reusable at every stage of the cycle (development, test, deploy).

conn = psycopg2.connect("dbname=postgres user=postgres password=postgres host=172.25.0.2")

You can acces it by service name as you said. Just remember to add links section and depends_on. Then you will have db_service resolved in hosts file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM