Access Docker postgres container from another cont

2020-04-10 03:04发布

I am trying to make a portable solution to having my application container connect to a postgres container. By 'portable' I mean that I can give the user two docker run commands, one for each container, and they will always work together.

I have a postgres docker container running on my local PC, and I run it like this,

docker run -p 5432:5432 -v $(pwd)/datadir:/var/lib/postgresql/data -e POSTGRES_PASSWORD=qwerty -d postgres:11

and I am able to access it from a python flask app, using the address 127.0.0.1:5432.

I put the python app in a docker container as well, and I am having trouble connecting to the postgres container.

Address 127.0.0.1:5432 does not work.

Address 172.17.0.2:5432 DOES work (172.17.0.2 is the address of the docker container running postgres). However I consider this not portable because I can't guarantee what the postgres container IP will be.

I am aware of the --add-host flag, but it is also asking for the host-ip, which I want to be the localhost (127.0.0.1). Despite several hits on --add-host I wasn't able to get that to work so that the final docker run commands can be the same on any computer they are run on.

I also tried this: docker container port accessed from another container

My situation is that the postgres and myApp will be containers running on the same computer. I would prefer a non-Docker compose solution.

1条回答
霸刀☆藐视天下
2楼-- · 2020-04-10 03:33

The comment from Truong had me try that approach (again) and I got it working. Here are my steps in case it helps out another. The crux of the problem was needing one container to address another container in a way that was static (didn't change). Using user defined network was the answer, because you can name a container, and thus reference that container IP by that name.

My steps,

docker network create mynet
docker run --net mynet --name mydb -v $(pwd)/datadir:/var/lib/postgresql/data -e POSTGRES_PASSWORD=qwerty -d postgres:11

Now the IP address of the postgres database is mydb, and all the ports of this container are exposed to any other container running in this network.

Now add the front end app,

docker run --net mynet -ti -p 80:80 -v mydockerhubaccount/myapp
查看更多
登录 后发表回答