docker-compose ports和expose的区别

转自 https://www.awaimai.com/2138.html

docker-compose中有两种方式可以暴露容器的端口:ports和expose。

  • ports
    ports暴露容器端口到主机的任意端口或指定端口,用法:
  • ports:
      - "80:80"         # 绑定容器的80端口到主机的80端口
      - "9000:80"       # 绑定容器的80端口到主机的9000端口
      - "443"           # 绑定容器的443端口到主机的任意端口,容器启动时随机分配绑定的主机端口号
    

    不管是否指定主机端口,使用ports都会将端口暴露给主机和其他容器

  • expose
    expose暴露容器给link到当前容器的容器,或者暴露给同一个networks的容器,用法:
  • expose:
      - "3000"
      - "8000"
    

    以上指令将当前容器的端口3000和8000暴露给其他容器

    和ports的区别是,expose不会将端口暴露给主机,主机无法访问expose的端口

    以下的docker-compose.yml的作用是使用keycloak-gatekeepertomcat做一个代理认证。tomcat服务使用expose暴露了8080端口;而tomcat-proxy服务使用ports暴露了3000端口并映射到host的8080端口。 同时tomcat-proxy容器和tomcat容器是在同一个容器网络平面中的。
    由于expose并没有映射容器端口到主机端口,因此在host上直接访问127.0.0.0:8080并不会直接访问tomcat服务
    在该示例中, 访问127.0.0.1:8080会走到tomcat-proxy服务,在tomcat-proxy上完成认证后,通过配置的upstream-url参数走容器网络平面跳转到tomcat服务。

    version: "3"
    services:
      tomcat:
        image: tomcat
        container_name: tomcat
        restart: always
        expose:
          - 8080
      tomcat-proxy:
        container_name: tomcat-proxy
        image: keycloak/keycloak-gatekeeper
        restart: unless-stopped
        command: >
          --discovery-url=https://keycloak.dev.com/auth/realms/demo
          --upstream-url=http://tomcat:8080
          --redirection-url=http://hello-world.example.org:8080
          --client-id=gatekeeper
          --client-secret=xxxxxxxxxx
          --encryption-key=xxxxxxxxxx
          --cookie-domain=example.org
          --listen=0.0.0.0:3000
          --enable-refresh-tokens=true
          --enable-encrypted-token=true
          --enable-logout-redirect=true
          --enable-token-header=false
          --enable-authorization-header=false
          --secure-cookie=false
          --forbidden-page=/forbidden.html.tmpl
          --resources="uri=/*"