如何为Docker postgres实例指定其他端口?

时间:2019-03-12 06:05:23

标签: docker docker-compose

我正在尝试使每个这样的几个在线线程在不同的端口(5433而不是默认的5432)上运行一个postgres容器: https://github.com/docker-library/postgres/issues/196#issuecomment-310209118

(端口更改的原因是因为我离开运行的不相关项目已经在使用端口5432,所以我希望能够在多个项目上同时运行rspec。)

在我的测试ENV中,我有 DATABASE_URL = postgresql:// postgres:@ db.local:5433 / test_agile_self

使用端口5432时一切正常(在DATABASE_URL和docker-compose.yml中)

将端口更改为5433后,当我运行rspec时,我得到:

PG::ConnectionBad:
  could not connect to server: Connection refused
    Is the server running on host "db.local" (172.22.0.2) and accepting
    TCP/IP connections on port 5433?
# ./spec/spec_helper.rb:62:in `block (2 levels) in <top (required)>'

该容器确实确实在端口5433和IP地址172.22.0.2上运行:

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
a8f5dee227e8        postgres:10.5       "docker-entrypoint.s…"   27 minutes ago      Up 14 seconds       0.0.0.0:5433->5432/tcp   zarc_db.local_1
$ docker inspect a8f5dee227e8 | grep "IPAddress"
            "SecondaryIPAddresses": null,
            "IPAddress": "",
                    "IPAddress": "172.22.0.2",

根据上面的链接,我的docker-compose.yml使用ports: "5433:5432"

#docker-compose.yml
version: '3'
services:
  web:
    build: .
    ports:
      - "3010:3010"
    volumes:
      - .:/my_app
    links:
      - db.local
    depends_on:
      - db.local

  db.local:
    image: postgres:10.5
    ports:
      - "5433:5432"

如果我在这两个位置(ENV和docker-compose.yml)将5433改回到5432,它将再次起作用。

这是在运行Mohave 10.14.3和Docker 18.09.2的Mac上

2 个答案:

答案 0 :(得分:3)

在容器内部,因此在$('.area li').on('click', function () { document.getElementById('displayValue').value = this.options[this.selectedIndex].text; document.getElementById('idValue').value = this.options[this.selectedIndex].text; }) 中,端口需要保持不变5432。在DATABASE_URL中,您仅使用给定的端口将现有端口5432映射为外界5543。

docker-compose

答案 1 :(得分:1)

在您的docker-compose中,您可以添加以下内容:(长语法)

ports:  
  - target: 80
    published: 8080
    protocol: tcp
    mode: host
  

在哪里

     
      
  • 目标:容器内的端口
  •   
  • 已发布:已公开的端口
  •   
  • 协议:端口协议(tcp或udp)
  •   
  • 模式:用于在每个节点上发布主机端口的主机,或用于输入群集模式端口以平衡负载的主机。
  •   

或者单行:(短语法)

ports:
  - "4040:5432" # HOST:CONTAINER
  

在哪里

     
      
  • 4040是要在主机上暴露的端口
  •   
  • 5432的端口暴露在容器上
  •   

注意:

当使用低于60的容器端口时,您可能会遇到错误的结果,因为YAML会将xx:yy格式的数字解析为以60为底的值。因此,我们建议始终将端口映射明确指定为字符串。

相关问题