Docker-compose端口转发 [英] Docker-compose port forwarding

查看:326
本文介绍了Docker-compose端口转发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站托管在生产共享托管上。该网站通过代码中的 localhost 连接到数据库。在我的docker-compose中,我有一个 php:5.6-apache mysql:5.6 实例。

I have a website hosted on shared hosting on production. The website connects to the database via localhost in the code. In my docker-compose I have a php:5.6-apache and mysql:5.6 instance.

是否仍然要告诉docker-compose将Web容器上的端口3306转发到db容器上的3306,以便当Web容器在3306上连接到localhost时被发送到3306上的db并同时将Web容器上的端口80共享给外界?

Is there anyway to tell docker-compose to have port 3306 on the web container port forwarded to 3306 on the db container so that when the web container ties to connect to localhost on 3306 it gets sent to db on 3306 and also share port 80 on the web container to the outside world?

当前docker-compose.yml:

Current docker-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

当前错误:


错误:对于Web无法为服务Web创建容器:冲突的选项:端口发布和容器类型网络模式

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


推荐答案

是可以的。您需要使用 network_mode 选项。参见下面的示例

Yes it is possible. You need to use the network_mode option. See the below example

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 服务本身上进行。

network_mode: service:db instructs docker to not assign the app services it own private network. Instead let it join the network of db service. So any port mapping that you need to do, needs to happen on the db service itself.

我通常使用的方式不同,我创建了一个 base 服务,该服务运行无限循环,而 db app 服务都在基础服务网络上启动。所有端口映射都需要在基本服务上进行。

The way I usually use it is different, I create a base service which runs a infinite loop and the db and app service both are launched on base service network. All ports mapping need to happen at the base service.

这篇关于Docker-compose端口转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆