无法连接到postgres容器
我在docker-compose.yml
定义postgres
服务器:
db: image: postgres:9.5 expose: - 5432
然后在另一个docker集装箱我试图连接到这个postgres容器。 但它给出了一个警告的错误:
Is the server running on host "db" (172.22.0.2) and accepting data-service_1 | TCP/IP connections on port 5432?
为什么容器不能通过提供的信息连接到另一个( host
=“db”和port
= 5432
)?
PS Full docker-compose.yml
:
version: "2" services: data-service: build: . depends_on: - db ports: - "50051:50051" db: image: postgres:9.5 depends_on: - data-volume environment: - POSTGRES_USER=cobrain - POSTGRES_PASSWORD=a - POSTGRES_DB=datasets ports: - "8000:5432" expose: - 5432 volumes_from: - data-volume # - container:postgres9.5-data restart: always data-volume: image: busybox command: echo "I'm data container" volumes: - /var/lib/postgresql/data
解决scheme#1。 相同的文件。
为了能够访问db
容器,你必须在docker-compose.yml
上下文中定义你的其他容器。 当容器启动时,每个容器都获得映射到/etc/hosts
所有其他容器。
做就是了
version: '2' services: web: image: your/image db: image: postgres:9.5
如果你不希望把你的其他容器放到同一个docker-compose.yml
,还有其他解决scheme:
解决scheme#2。 IP
docker inspect <name of your db container>
并在结果列表中查找IPAddress
指令。 使用该IPAddress
作为主机连接到。
解决scheme#3。 networking
让你的容器join同一个networking。 为此,在每项服务下,定义:
services: db: networks: - myNetwork
不要忘记更改每个容器的db
。
我通常在开发过程中使用第一个解决scheme。 我使用apache+php
作为一个容器, pgsql
作为另一个容器,每个项目都有一个单独的数据库。 我不会启动多个docker-compose.yml
设置,因此在这种情况下,将两个容器定义在一个.yml
configuration文件中是完美的。
依赖于是不正确的。 我会尝试使用像LINKS和环境的其他参数:
version: "2" services: data-service: build: . links: - db ports: - "50051:50051" volumes_from: ["db"] environment: DATABASE_HOST: db db: image: postgres:9.5 environment: - POSTGRES_USER=cobrain - POSTGRES_PASSWORD=a - POSTGRES_DB=datasets ports: - "8000:5432" expose: - 5432 #volumes_from: #- data-volume # - container:postgres9.5-data restart: always data-volume: image: busybox command: echo "I'm data container" volumes: - /var/lib/postgresql/data
这一个适用于我(不postgres,但MySQL)