Start a container with published ports
In this step, we will learn how to start a Docker container and publish its ports to the host machine. Publishing ports allows external access to services running inside the container.
First, let's pull the nginx
image from Docker Hub. This image contains a simple web server that we can use for demonstration.
docker pull nginx
You should see output indicating that the image is being downloaded. Once the download is complete, you can verify that the image is available locally by running:
docker images
Now, we will start an nginx
container and publish port 80 inside the container to port 8080 on the host machine. The -d
flag runs the container in detached mode (in the background), the -p
flag maps the ports, and nginx
is the image name.
docker run -d -p 8080:80 nginx
The output will be the container ID. This means the container has started successfully and its internal port 80 is accessible via port 8080 on your LabEx VM.
To verify that the web server is running and accessible, you can use curl
to access the published port on the host machine.
curl http://localhost:8080
You should see the default Nginx welcome page HTML output in your terminal. This confirms that the port mapping is working correctly and you can access the service running inside the container from the host.