从外部连接到Docker容器中的Postgresql [英] Connecting to Postgresql in a docker container from outside
问题描述
我在Docker容器中的服务器上安装了Postgresql.如何从外部(即从本地计算机)连接到它?我应该应用什么设置来允许它?
I have Postgresql on a server in a docker container. How can I connect to it from the outside, that is, from my local computer? What setting should I apply to allow that?
推荐答案
您可以通过以下方式运行Postgres(映射端口):
You can run Postgres this way (map a port):
docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres
因此,现在您已将容器的端口5432映射到服务器的端口5432. -p <host_port>:<container_port>
.因此,现在您可以从public-server-ip:5432
So now you have mapped the port 5432 of your container to port 5432 of your server. -p <host_port>:<container_port>
.So now your postgres is accessible from your public-server-ip:5432
要测试: 运行postgres数据库(上面的命令)
To test: Run the postgres database (command above)
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
05b3a3471f6f postgres "/docker-entrypoint.s" 1 seconds ago Up 1 seconds 0.0.0.0:5432->5432/tcp some-postgres
进入容器并创建数据库:
Go inside your container and create a database:
docker exec -it 05b3a3471f6f bash
root@05b3a3471f6f:/# psql -U postgres
postgres-# CREATE DATABASE mytest;
postgres-# \q
转到您的本地主机(那里有一些工具或psql客户端).
Go to your localhost (where you have some tool or the psql client).
psql -h public-ip-server -p 5432 -U postgres
(密码mysecretpassword)
(password mysecretpassword)
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+------------+------------+-----------------------
mytest | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres
因此,您正在从本地主机访问数据库(该数据库在服务器上的docker中运行).
So you're accessing the database (which is running in docker on a server) from your localhost.
在此帖子中详细说明.
这篇关于从外部连接到Docker容器中的Postgresql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!