Docker-Compose 容器 ip 地址与容器名称 [英] Docker-Compose container ip address with container name

查看:133
本文介绍了Docker-Compose 容器 ip 地址与容器名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 docker-compose 有两个服务,和 docker-compose.yml 用容器名称定义环境变量 ip 地址,

My docker-compose have a two service, and docker-compose.yml define enviroment variable ip address with container name,

 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

但变量见con_ip"而不是 127.0.0.3

But variable see "con_ip" not 127.0.0.3

推荐答案

我认为您没有正确使用环境变量.请参考compose中的环境变量.

I don't think that you are properly using environment variables. Please refer environment variables in compose.

您只需使用该容器的服务名称即可从另一个容器访问该容器.这是推荐的方式.

You can access one container from other container simply by using service name of that container. And this is the recommended way.

但是如果您出于自己的原因更喜欢IP地址,我告诉您如何设置容器的静态IP地址,但我不建议这样做.

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.

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

这将为您的容器分配所需的 IP 地址.API 将位于 127.0.0.3web 将位于 127.0.0.4

This will assign the required IP-addresses to your containers. API will be at 127.0.0.3 and web will be at 127.0.0.4

如果您想从 Web 容器内部访问名为 api 的服务,那么您可以使用我们在此处分配的 IP 地址.http://127.0.0.3:80/ 或者您也可以使用 http://api:80/

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. http://127.0.0.3:80/ or you can also use http://api:80/

api 用于代替 IP 地址,因为它是服务名称,当没有给出主机名时,服务名称将作为默认主机名.如果您想了解主机名,请参阅这个问题.

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. If you want to know about hostnames refer to this question.

这篇关于Docker-Compose 容器 ip 地址与容器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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