Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Docker accesses the container externally


May 22, 2021 Docker From entry to practice



Some network apps can run in the container, and for external access to them, -P -p or -p parameters.

When using the -P tag, Docker randomly 49000~49900 to a network port open to the internal container.

Using docker ps you can see that the local host's 49155 is mapped to the container's 5000 port. Access to the 49155 port of the machine provides access to the interface provided by the in-container web app.

$ sudo docker run -d -P training/webapp python app.py
$ sudo docker ps -l
CONTAINER ID  IMAGE                   COMMAND       CREATED        STATUS        PORTS                    NAMES
bc533791f3f5  training/webapp:latest  python app.py 5 seconds ago  Up 2 seconds  0.0.0.0:49155->5000/tcp  nostalgic_morse

Similarly, you docker logs through the docker logs command.

$ sudo docker logs -f nostalgic_morse
* Running on http://0.0.0.0:5000/
10.0.2.2 - - [23/May/2014 20:16:31] "GET / HTTP/1.1" 200 -
10.0.2.2 - - [23/May/2014 20:16:31] "GET /favicon.ico HTTP/1.1" 404 -

-p (in uppercover) you can specify which ports to map, and you can bind only one container on a specified port. Supported ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort

Map all interface addresses

Using hostPort:containerPort the local 5000 ports are mapped to the container's 5000 ports and can be executed

$ sudo docker run -d -p 5000:5000 training/webapp python app.py

All addresses on all local interfaces are bound by default.

Map to the specified port of the specified address

You ip:hostPort:containerPort to specify that the map uses a specific address, such as the localhost address 127.0.0.1

$ sudo docker run -d -p 127.0.0.1:5000:5000 training/webapp python app.py

Map to any port with the specified address

Using ip::containerPort bind any port of localhost to the container's 5000 ports, the local host automatically assigns a port.

$ sudo docker run -d -p 127.0.0.1::5000 training/webapp python app.py

You can also use the udp tag to specify the udp port

$ sudo docker run -d -p 127.0.0.1:5000:5000/udp training/webapp python app.py

View the mapping port configuration

Use docker port see the currently mapped port configuration, or you can view the bound address

$ docker port nostalgic_morse 5000
127.0.0.1:49155.

Attention:

  • Containers have their own internal network and ip address docker inspect be obtained using docker inspect, and Docker can also have a variable network configuration).)
  • The -p tag can be used multiple times to bind multiple ports

For example

$ sudo docker run -d -p 5000:5000  -p 3000:80 training/webapp python app.py