验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

docker中怎么配置hosts

阅读:684 来源:乙速云 作者:代码code

docker中怎么配置hosts

配置的方法

方法一:启动容器的时候加上“--add-host”

示例:

docker run --add-host='www.lyb-geek.com:127.0.0.1' --add-host='www.lyb-geek.cn:192.168.3.1' --name hello-docker -it 192.168.0.1:5002/lybgeek/hello-docker:1.0

方法二:如果是通过docker-compose启动容器,可以配置extra_hosts属性

示例

version: '3.7'
services:
  hello-docker:
    restart: always
    image: 192.168.0.1:5002/lybgeek/hello-docker:1.0
    extra_hosts:
    - "www.lyb-geek.com:127.0.0.1"
    - "www.lyb-geek.cn:192.168.3.1"
    container_name: hello-docker
    network_mode: bridge
    ports:
     - "80:80"
    environment:
     - ENV=dev

方法三:如果是通过k8s来管理容器,则在可以在创建pod的yaml文件通过hostAliases添加域名IP映射

示例:

apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: dev
  name: hello-docker-deployment
  labels:
    app: hello-docker
spec:
  replicas: 3
  selector:
    matchLabels:
      app: hello-docker
  template:
    metadata:
      labels:
        app: hello-docker
    spec:
      hostAliases:
      - hostnames:
        - www.lyb-geek.com
        ip: 127.0.0.1
      - hostnames:
        - www.lyb-geek.cn
        ip: 192.168.3.1
      imagePullSecrets:
      - name: default-secret
      containers:
      - name: hello-docker
        image: 192.168.0.1:5002/lybgeek/hello-docker:1.0
        imagePullPolicy: Always
        ports:
         - containerPort: 80
        env:
          - name: ENV
            value: "dev"

核心配置

 spec:
      hostAliases:
      - hostnames:
        - www.lyb-geek.com
        ip: 127.0.0.1
      - hostnames:
        - www.lyb-geek.cn
        ip: 192.168.3.1

配置内容的解释如下图

docker中怎么配置hosts

总结

不知道大家有没有好奇为什么没介绍通过dockerfile的方式,因为dockerfile的方式,我试过在dockerfile文件中配置

RUN echo 'www.lyb-geek.com:127.0.0.1' >> /etc/hosts

不过没生效。也试过将hosts的文件放在项目目录下

通过配置如下内容

COPY hosts /etc/hosts
RUN echo 'www.lyb-geek.com:127.0.0.1' >> /etc/hosts

不过没鸟用。可能配法不对,也有可能是因为被k8s影响到了。不过如果容器是通过k8s来管理,推荐直接通过 配置hostAliases这种方式。其实还有一种方式,就是进入容器内部,直接改hosts文件,就跟我们操作宿主机一样。不过这种方式不推荐就是,因为容器一重启或者销毁,配置就丢了

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>