通过 docker-compose 为 docker 容器提供静态 IP [英] Provide static IP to docker containers via docker-compose

查看:70
本文介绍了通过 docker-compose 为 docker 容器提供静态 IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为容器提供静态 IP 地址.我知道我必须创建一个自定义网络.我创建了它,并且桥接接口在主机(Ubuntu 16.x)上启动.容器从该子网获取 IP,但不是我提供的静态 IP.

I'm trying to provide static IP address to containers. I understand that I have to create a custom network. I create it and the bridge interface is up on the host machine (Ubuntu 16.x). The containers get IP from this subnet but not the static I provided.

这是我的 docker-compose.yml:

Here is my docker-compose.yml:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
     - vpcbr

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
     - vpcbr
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1
         aux_addresses:
          mysql: 10.5.0.5
          apigw-tomcat: 10.5.0.6

容器得到 10.5.0.2 和 10.5.0.3,而不是 5 和 6.

The containers get 10.5.0.2 and 10.5.0.3, instead of 5 and 6.

推荐答案

请注意,我不建议在 Docker 中为容器使用固定 IP,除非您正在做一些允许从容器网络外部路由到内部网络的操作(例如 macvlan).DNS 已经用于容器网络内部的服务发现,并支持容器扩展.在容器网络之外,您应该使用主机上的公开端口.有了这个免责声明,这里是你想要的撰写​​文件:

Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.5

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.6
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1

这篇关于通过 docker-compose 为 docker 容器提供静态 IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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