Add or remove a published port
In this step, you will learn how to add or remove a published port for a Docker service. Publishing a port makes a port inside the container accessible from outside the Docker Swarm cluster. This is essential for exposing your application to users or other services.
Our current my-service
doesn't have any published ports because it just runs a simple echo
command and exits. To demonstrate publishing ports, let's create a new service that runs a simple web server. We will use the nginx
image for this.
First, pull the nginx
image:
docker pull nginx
Now, let's create a new service named web-service
and publish port 80 of the container to port 8080 on the host.
docker service create --name web-service --publish 8080:80 nginx
This command creates a service named web-service
using the nginx
image. The --publish 8080:80
flag maps port 80 inside the container to port 8080 on the host.
You should see output indicating the service ID.
To verify that the port is published, you can inspect the service:
docker service inspect web-service
Look for the EndpointSpec
section in the output. You should see an entry under Ports
that shows the published port mapping (e.g., PublishedPort: 8080
, TargetPort: 80
).
Now, let's remove the published port from the web-service
. We can do this using the docker service update
command with the --publish-rm
flag, specifying the target port inside the container.
docker service update --publish-rm 80 web-service
This command removes the port mapping for port 80 inside the container.
You should see output indicating that the service was updated.
To verify that the port has been removed, inspect the service again:
docker service inspect web-service
The EndpointSpec
section should no longer show the port mapping you just removed.