2017-08-02 135 views
1

我有一個網站託管在生產共享主機上。該網站通過代碼中的localhost連接到數據庫。在我的docker-compose中,我有一個php:5.6-apachemysql:5.6實例。Docker-compose端口轉發

有無論如何告訴docker-compose將Web容器端口上的端口3306轉發給db容器上的3306,以便當web容器連接到3306上的localhost時,它將被髮送到3306上的db,將Web容器上的端口80共享給外部世界?

當前泊塢窗,compose.yml:

version: "3" 

services: 
    web: 
    build: . 
    #image: php:5.6-apache 
    ports: 
    - "8080:80" 
    environment: 
    - "APP_LOG=php://stderr" 
    - "LOG_LEVEL=debug" 
    volumes: 
    - .:/var/www/html 
    network_mode: service:db # See https://stackoverflow.com/a/45458460/95195 
# networks: 
#  - internal 
    working_dir: /var/www 
    db: 
    image: mysql:5.6 
    ports: 
    - "3306:3306" 
    environment: 
     - "MYSQL_XXXXX=*****" 
    volumes: 
     - ./provision/mysql/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d 
# networks: 
#  - internal 

networks: 
    internal: 
    driver: bridge 

當前出錯:

ERROR: for web Cannot create container for service web: conflicting options: port publishing and the container type network mode

回答

2

是的,它是可能的。您需要使用network_mode選項。見下面的例子

version: '2' 

services: 
    db: 
    image: mysql 
    environment: 
     MYSQL_ROOT_PASSWORD: root 
    ports: 
     - "80:80" 
     - "3306:3306" 
    app: 
    image: ubuntu:16.04 
    command: bash -c "apt update && apt install -y telnet && sleep 10 && telnet localhost 3306" 
    network_mode: service:db 

輸出

app_1 | Trying 127.0.0.1... 
app_1 | Connected to localhost. 
app_1 | Escape character is '^]'. 
app_1 | Connection closed by foreign host. 

network_mode: service:db指示碼頭工人不分配app服務它自己的專用網絡。反而讓它加入db服務的網絡。因此,您需要執行的任何端口映射都需要在db服務本身上發生。

我通常使用的方式不同,我創建了一個base服務,該服務運行一個無限循環,並且dbapp服務都在基本服務網絡上啓動。所有端口映射都需要在基本服務中進行。

+0

看來這個標誌與端口不兼容。我想這樣做,但也有Web容器端口80可訪問世界。我無法準確理解network_mode:service如何從文檔中執行操作。 –

+0

更新了有關端口的更多詳細信息。見upate –