Geek Logbook

Tech sea log book

How to Keep a Docker Container Running Persistently

When working with Docker, you may have noticed that some containers stop as soon as you exit the shell. This is because Docker considers the container’s main process to have finished. In this post, we will explain why this happens and how to keep your container running persistently, so you can reconnect whenever you need.

Why Containers Exit After You Leave Bash

When you run a container with docker run -it IMAGE bash, Docker starts a single process: bash. Once you type exit, bash terminates, and Docker stops the container. This behavior is by design — containers are supposed to run a single main process, and when that process finishes, the container ends.

Option 1: Run a Persistent Command

To keep the container running, you need a command that stays alive. A common trick is to run:

docker run -dit --name my_container IMAGE tail -f /dev/null

Here is what the flags mean:

  • -d: detached mode, runs in the background.
  • -i: keeps STDIN open.
  • -t: allocates a pseudo-TTY.
  • tail -f /dev/null: a dummy command that never exits, keeping the container alive.

Now you can attach to it whenever you want:

docker exec -it my_container bash

And when you exit bash, the container remains Up.

Option 2: Using Docker Compose

For a more reproducible setup, you can create a simple docker-compose.yml:

version: '3.8'
services:
  glue-libs:
    image: public.ecr.aws/glue/aws-glue-libs:5
    container_name: quirky_booth
    command: tail -f /dev/null

Start it with:

docker compose up -d

And stop it with:

docker compose down

This approach makes it easy to restart the container consistently without remembering long docker run commands.

Option 3: Commit and Relaunch an Existing Container

If you already have a container with data you want to keep:

docker commit <container_id> my_persistent_image

docker run -dit --name my_container my_persistent_image tail -f /dev/null

This creates a new image from the stopped container and runs it in persistent mode.

Final Thoughts

Keeping a container running is about ensuring its main process never exits. Whether you use tail -f /dev/null, docker-compose, or a committed image, these methods give you a stable container you can reconnect to any time.

Tags: