- Automatically clean up ephemeral containers
- Customize container hostnames
- Control container restarts with various policies
- Inspect Docker events for troubleshooting
- Copy files between host and containers
- Expose ports using random and static mappings
Automatically Remove Ephemeral Containers with --rm
When running short-lived or CI/CD containers, you can use --rm to automatically delete them upon exit. This helps keep your environment clean and free of stale containers.
Using
--rm is ideal for one-off or CI tasks. Remember that you won’t be able to inspect logs or the filesystem after the container exits.Setting Container Name vs. Hostname
Docker allows you to assign both a unique container name and an internal hostname:Container names must be unique per host, but you can reuse the same internal hostname across multiple containers.
Restart Policies
Docker’s--restart flag offers fine-grained control over container uptime. Below is a summary of each policy:
| Policy | Description |
|---|---|
no | (default) Container will not restart after exit. |
on-failure[:N] | Restart only on non-zero exit status. Optionally limit retries to N. |
always | Always restart the container regardless of exit code or Docker daemon restarts. |
unless-stopped | Like always, but the container won’t restart if you manually stopped it. |
1. --restart=no (Default)
2. --restart=on-failure
3. --restart=always
4. --restart=unless-stopped
casefour stays down after a manual stop.
Use
always or unless-stopped for critical services. Excessive restart loops on failure can degrade performance—consider on-failure with a retry limit.Inspecting Docker Events
To diagnose restart loops or networking events, view real-time Docker system events:Copying Files Between Host and Container (docker cp)
You don’t need an interactive shell to move files; docker cp handles it directly.
Host → Container
Container → Host
Publishing Ports
By default, containers don’t expose ports to the host. You can use random or static port mappings:| Option | Description | Access URL |
|---|---|---|
| none | No mapping; container ports are isolated | Unreachable from host |
-P | Random high host port mapped to container’s port | http://<host-ip>:<random> |
-p | Static host-to-container port mapping (e.g., 82:80) | http://<host-ip>:82 |
No Port Mapping
Random Port Mapping (-P)
Static Port Mapping (-p)
Port Mapping on Restart
- With
-P, Docker may assign a different random port after restart. - With
-p, the mapping remains consistent.
For production services, always use
-p for predictable port assignments and easier firewall configuration.