简体   繁体   English

带有容器名称的Docker-Compose容器IP地址

[英]Docker-Compose container ip address with container name

My docker-compose have a two service, and docker-compose.yml define enviroment variable ip address with container name, 我的docker-compose提供两项服务,docker-compose.yml使用容器名称定义环境变量ip地址,

 version: '2'

services:
  api:
    build: ./api/
    command: python3 manage.py runserver
    volumes:
      - ./api:/code
    ports:
      - "8000:80"
    networks:
      - dock_net
    container_name: con_api

  web:
    build: ./web/
    command: python3 manage.py runserver
    volumes:
      - ./web:/code
    ports:
      - "8001:80"
    networks:
      - dock_net
    container_name: con_web
    environment:
        Ip:con_ip

networks:
  dock_net:
      driver: bridge

But variable see "con_ip" not 127.0.0.3 但是变量请参见“ con_ip”而不是127.0.0.3

I don't think that you are properly using environment variables. 我认为您没有正确使用环境变量。 Please refer environment variables in compose . 在compose中引用环境变量

You can access one container from other container simply by using service name of that container. 您只需使用该容器的服务名称就可以从其他容器访问一个容器。 And this is the recommended way. 这是推荐的方法。

But if you prefer IP addresses for your own reasons, I am telling you how to set the static ip address of container, i would not recommend it though. 但是,如果您出于自己的原因而喜欢IP地址,我会告诉您如何设置容器的静态IP地址,不过我不建议这样做。

version: '2'
services:
  api:
    build: ./api/
    command: python3 manage.py runserver
    volumes:
      - ./api:/code
    ports:
      - "8000:80"
    networks:
      - dock_net:
          ipv4_address: 127.0.0.3
    container_name: con_api

  web:
    build: ./web/
    command: python3 manage.py runserver
    volumes:
      - ./web:/code
    ports:
      - "8001:80"
    networks:
      - dock_net:
          ipv4_address: 127.0.0.4
    container_name: con_web

networks:
  dock_net:
    driver: bridge
    ipam:
     config:
       - subnet: 127.0.0.0/8
         gateway: 127.0.0.1

This will assign the required IP-addresses to your containers. 这会将所需的IP地址分配给您的容器。 API will be at 127.0.0.3 and web will be at 127.0.0.4 API将为127.0.0.3web127.0.0.4

EDIT: If you want to access service named api from inside the web container then you can use its ip address as we have allocated here. 编辑:如果您想从Web容器内部访问名为api服务,则可以使用它的IP地址,因为我们已经在此处分配了它。 http://127.0.0.3:80/ or you can also use http://api:80/ http://127.0.0.3:80/或您也可以使用http:// api:80 /

The api is used in place of IP address because its the service name and when no hostname is given, service name is taken as default hostname. 使用api代替IP地址是因为它是服务名称,如果没有提供主机名,则将服务名称作为默认主机名。 If you want to know about hostnames refer to this question. 如果您想了解主机名,请参考问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM