从外部连接到 docker 容器中的 Postgresql

编程入门 行业动态 更新时间:2024-10-27 19:21:36
本文介绍了从外部连接到 docker 容器中的 Postgresql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在 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> .所以现在你的 postgres 可以从你的 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

本文发布于:2023-10-14 12:24:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1491048.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接到   容器   docker   Postgresql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!