简体   繁体   中英

How to connect to dockerized database from outside of the docker network on local machine

I have created this docker container for my postgres database on my windows machine:

docker run -d -p 5432:5432 --rm --name pg_container -v C:\pgdata:/var/lib/postgresql/data --env-file ./database.env postgres:latest

And if I run docker exec -it pg_container bash and run psql command I can create a database name mydb (in the real situation, this is being created by a flask application).

If I run

docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' tma_pg_db_container

I will get 172.0.0.2

Now I want to connect directly to the database from outside of the container.

psql postgresql://postgres:<PASSWORD>@<IP_ADDRESS>:5432/tma_pg_db

What should I use for IP_ADDRESS ?

Please note that I have another psotgres database created on the system level and not in the container. For that one, I use localhost it, and works fine, it connects. If I use localhost, it connects to the system-level database not the container inside the docker container.

You should use localhost . That will connect to the port you published using the docker run -p option.

(If you are using a VM-based solution like Docker Machine or Docker Toolbox, you need its IP address instead; docker-machine ip will tell you what it is. If you're calling from a different host, use the physical host's IP address, the same way you would if the service wasn't running in a container.)

The two important corollaries to this are that (a) you don't need debugging tools like docker exec to interact with your database; and (b) you don't need to look up the docker inspect IP address (which also doesn't work in many common contexts).

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