How to access the local computer in Docker
This article is about how to access the local computer in Docker. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Question
Docker internal demand to access the local database, how to access. Using 127.0.0.1 is definitely not possible, because this refers to the container itself in the Docker container. Therefore, we need to go through the channels to solve the problem.
Solution
The following ways, according to the type of operating system, choose one of them.
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.Conf ig}} {{end}} 'bridge` [IMAGE]
Docker for Mac (17.12 +):
Docker.for.mac.host.internalMONGO_SERVER=docker.for.mac.host.internal# docker-compose.ymlversion: '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 2mure "DOCKER_HOST=$ (ip-4 addr show docker0 | grep-Po 'inet\ K [\ d.] +')"
Principle
If you want to know the principle, you need to understand the model of the computer network and the model implemented by docker. Docker actually implements a virtual bridge docker0. You need to find the virtual address of the external host on the bridge, that is, docker.for.mac.host.internal, through the bridge, so that you can access the external host in the container. If you are interested, you can understand the network principle of Docker, computer network principle and docker compose and so on.
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
Thank you for reading! This is the end of this article on "how to access this computer in Docker". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!