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

查看:383
本文介绍了通过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天全站免登陆