Run a container with a published port
Low risk
What do risk levels mean?
- Read-only
- Inspects state without changing anything.
- Low risk
- Reversible with a routine follow-up command.
- Medium risk
- Changes state; undo path documented.
- Destructive
- Deletes or overwrites; confirmation required.
Starts a detached container from an image and publishes one of its ports on the host, so services inside the container are reachable from localhost.
dockerrunportpublish
Parameters
Image reference to run, such as nginx:1.27.
Name to give the new container.
Port on the host to listen on.
Port the service listens on inside the container.
Commands
Check that no other container already publishes the chosen host port
docker ps --filter publish=<host_port>Start the container in the background with the port published on the host
docker run --detach --name <name> --publish <host_port>:<container_port> <image>Verification
docker port <name>The container port is mapped to the chosen host port, and docker ps shows the container as Up.
Undo
Stop and remove the container started by this recipe
docker rm --force <name>Pitfalls
- If the host port is already in use the run fails with "port is already allocated"; pick another host port or stop the conflicting container.
- The image is pulled automatically if missing, which can take time on first run.
- Without a --restart policy the container stays stopped after a daemon or host restart.