To expose a container’s network port to the host system, you need to use the -p option with the docker run command. The -p option specifies the port to expose on the host system and the port to map to inside the container. Here are the steps to expose a container’s network port to the host system:
Open a terminal window and run the docker run command with the following syntax:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
The IMAGE argument specifies the name and tag of the Docker image to use for the container. The OPTIONS and COMMAND arguments are optional and can be used to customize the behavior of the container.
Use the -p option to specify the host port and container port to map. The -p option takes two arguments, separated by a colon (:). The first argument is the port to expose on the host system, and the second argument is the port to map to inside the container.
For example, to expose port 80 on the host system and map it to port 80 inside the container, you would run the following command:
docker run -p 80:80 IMAGE
This command starts a new Docker container based on the specified IMAGE, exposes port 80 on the host system, maps port 80 inside the container to port 80 on the host system, and runs the container.
Wait for the Docker container to start. This may take a few seconds, depending on the size of the image and the resources available on your system.
Verify that the container’s network port is exposed to the host system by running a web browser or other network tool and connecting to http://localhost:80. This should display the web server running inside the container.
Here are some additional options that you can use with the -p option:
IP:HOST_PORT:CONTAINER_PORT: This option allows you to specify a custom IP address to use for the host system, as well as custom host and container ports to map.
-P: This option exposes all of the ports specified in the Dockerfile or the image metadata to random ports on the host system.
For example, to map port 8080 on the host system to port 80 inside the container and use a custom IP address of 192.168.1.100, you would run the following command:
docker run -p 192.168.1.100:8080:80 IMAGE
This command starts a new Docker container based on the specified IMAGE, exposes port 8080 on the host system with a custom IP address of 192.168.1.100, maps port 80 inside the container to port 8080 on the host system, and runs the container.