How do I access the specific method of the native of host in Docker
- 2020-12-16 06:13:33
- OfStack
Question
Docker needs to access the native database, how to access. Using 127.0.0.1 is definitely not possible, as this refers to the container itself within the Docker container. Therefore, the need to move the channel to solve.
Solution
The following methods, according to the type of operating system, select its 1.
DockerFile:
RUN /sbin/ip route|awk '/default/ { print $3,"\tdockerhost" }' >> /etc/hosts
RunTime:
(may not use) docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print $3}'` [my container]
(useful) docker run --add-host=dockerhost:`docker network inspect --format='{{range .IPAM.Config}}{{.Gateway}}{{end}}' bridge` [IMAGE]
Docker for Mac (17.12+):
docker.for.mac.host.internal
MONGO_SERVER=docker.for.mac.host.internal
# docker-compose.yml
version: '3'
services:
api:
build: ./api
volumes:
- ./api:/usr/src/app:ro
ports:
- "8000"
environment:
- MONGO_SERVER
command: /usr/local/bin/gunicorn -c /usr/src/app/gunicorn_config.py -w 1 -b :8000 wsgi
Linux
# Solution 1
/sbin/ip route|awk '/default/ { print $3 }'
docker run --add-host dockerhost:`/sbin/ip route|awk '/default/ { print $3}'` [my container]
# Solution 2
-e "DOCKER_HOST=$(ip -4 addr show docker0 | grep -Po 'inet \K[\d.]+')"
Principle
To understand the principle, you need to understand the model of the computer network and the model of the docker implementation. docker internal docker0 actually realizes a virtual Bridges, need to find outside of the host machine through the bridge in the virtual address of the bridge, namely docker. for. mac. host. internal, container can access external host machine. If you are interested, you can learn about Docker's network principle, computer network principle and docker compose, etc.
Reference
[1].(stackoverflow)insert-docker-parent-host-ip-into-containers-hosts-file
[2].(stackoverflow)how-to-get-the-ip-address-of-the-docker-host-from-inside-a-docker-container