如何从外部主机连接到使用docker-compose创建的postgres

时间:2020-02-21 14:05:28

标签: postgresql docker docker-compose psql

我认为这个问题应该很容易解决,但是我正在拔头发。我有以下docker-compose:

version: "3"
services:

  pg-db:
    image: postgres:11
    environment:
      POSTGRES_PASSWORD: "postgres"
      POSTGRES_USER: "postgres"
      POSTGRES_DB: "postgres"
    ports:
      - 5432:5432
    #network_mode: host

然后我运行docker-compose up,它将启动容器

pg-db_1_78e7ec4a95e6 | 2020-02-21 13:53:53.928 UTC [1] LOG:  database system is ready to accept connections

我可以使用docker exec连接到它

docker exec -it docker_pg-db-compose_1_78e7ec4a95e6 psql -h pg-db -U postgres postgres

但是我无法通过“裸” psql连接到它:

psql postgresql://postgres:postgres@localhost:5432/postgres

psql: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?

psql postgresql://postgres:postgres@pg-dg:5432/postgres
psql: could not translate host name "pg-db" to address: Name or service not known

我尝试过使用network_mode,但没有帮助。

2 个答案:

答案 0 :(得分:3)

启动docker-compose之后,您需要执行以下操作获取docker容器ip:

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

然后您可以进行postgresql://postgres:postgres@<container idp>:5432/postgres的连接

答案 1 :(得分:0)

我正在使用Postgres DockerHub page中提供的docker-compose文件的修改版本。

version: '3.1'
services:
  db:
    image: postgres:11
    restart: always
    ports:
      - 5432:5432
    environment:
      POSTGRES_PASSWORD: postgres

当我运行docker-compose up时,会收到非常相似的“就绪”消息:

db_1  | 2020-02-21 14:34:17.826 UTC [1] LOG:  database system is ready to accept connections

这时,我可以使用psql连接到Postgres。

$ psql -h localhost -U postgres
Password for user postgres: 
psql (12.2, server 11.7 (Debian 11.7-1.pgdg90+1))
Type "help" for help.

postgres=#

我还可以使用您提供的连接字符串和postico进行连接:

postico 1 postico 2

差异微妙,我不确定restart政策在这里是否有任何区别,请尝试一下。