Skip to main content
In this lesson, we’ll explore advanced Docker flags and best practices for managing containers. You’ll learn how to:
  • 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.
Stop and watch it disappear:
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:

1. --restart=no (Default)

The container will remain stopped until you manually start it again.

2. --restart=on-failure

The container automatically restarts if it exits with a non-zero status.

3. --restart=always

Regardless of exit reason or daemon restart, the container will be restarted.

4. --restart=unless-stopped

Even if Docker restarts, 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:
Sample output: 2020-05-04T08:38:43.747Z network connect cf10… (container=2daf…, name=bridge) 2020-05-04T08:38:43.976Z container start … (image=ubuntu, name=casethree) 2020-05-04T08:39:43.633Z network connect cf10… (container=74b0…, name=bridge) 2020-05-04T08:39:43.890Z container start … (image=ubuntu, name=casefour)

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:

No Port Mapping

Accessing via host IP will fail.

Random Port Mapping (-P)

Docker picks a random port (e.g., 32768) for container port 80.

Static Port Mapping (-p)

Now host port 82 forwards to container port 80.

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.

References

We hope this lesson helps you master advanced Docker container operations!

Watch Video