foreword
I don’t know if you have encountered such a scenario. The project deployed in the docker environment needs to access some external resources through the domain name, but because dns resolution is not configured, it needs to be accessed by configuring hosts. This article will talk about the ways in which hosts can be configured in the docker container
Configuration method
Method 1: Add "–add-host" when starting the container
Example:
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
Method 2: If you start the container through docker-compose, you can configure the extra_hosts property
example
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
3. Method 3: If you manage the container through k8s, you can add domain name IP mapping through hostAliases in the yaml file of pod creation
Example:
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"
core configuration
spec:
hostAliases:
- hostnames:
- www.lyb-geek.com
ip: 127.0.0.1
- hostnames:
- www.lyb-geek.cn
ip: 192.168.3.1
The explanation of the configuration content is as follows
Summarize
I don’t know if you are curious why the way of passing the dockerfile is not introduced, because of the way of the dockerfile, I have tried to configure it in the dockerfile
RUN echo 'www.lyb-geek.com:127.0.0.1' >> /etc/hosts
But it didn't work. Also tried putting the hosts file in the project directory
By configuring the following
COPY hosts /etc/hosts
RUN echo 'www.lyb-geek.com:127.0.0.1' >> /etc/hosts
But no bird. The matching method may be wrong, or it may be affected by k8s.
However, if the container is managed by k8s, it is recommended to configure hostAliases directly . In fact, there is another way, which is to enter the container and directly modify the hosts file, just like we operate the host. However, this method is not recommended, because once the container is restarted or destroyed, the configuration will be lost