English
Note

In this guide on how to keep your Docker container running indefinitely! If you've ever faced the challenge of dealing with short-lived containers, worry no more - we've got you covered!

How to Keep Docker Container Running Indefinitely? cover image

In this guide, we'll show you how to extend the lifespan of your containers using different methods.

You'll learn the importance of persistent containers and discover powerful techniques to keep them running smoothly in the background. Whether you're a seasoned DevOps pro or just starting with containerization, these insights will elevate your Docker game.

But before we dive deep into how to keep docker containers running, let's look at how long containers run for normally and why keep them running in the background.

How Long Do Normal Containers Run?

The short answer is: Docker containers can run for as long as you need them to.

Let's look at the longer answer.

They are designed to run individual applications or services in an isolated environment, which means they can keep running until you decide to stop them.

The length of time a normal Docker container runs depends on various factors, including how it is configured and the application it hosts.

By default, Docker containers run as long as the process inside the container is active. Once the main function within the container stops or exits or is forcefully done by the admin, the container will stop.

Also Read: The Only Docker Commands Cheat Sheet You'll Ever Need

Common Scenarios for Container Lifetimes

Let's look at different types of containers based on their lifetimes.

Short-lived Containers

These containers are designed to perform a specific task or job and then exit.

Example: A Docker container that runs a simple Python script and then exits.

FROM python:3.9-slim
COPY script.py /app/script.py
CMD ["python", "/app/script.py"]

Script.py file

print("Hello, World!")

Also Read: Docker Image vs Container

Long-running Containers

These kinda containers are designed to run continuously for extended periods, hosting services or your applications.

Examples include web servers, databases, or other services that need to remain operational as long as the application is running.

Example: A Docker container running a basic Nginx web server.

FROM nginx:latest
COPY website/ /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Place the website files inside a directory called "website" located in the same directory as the Dockerfile.

Also Read: What are Init Containers?

Interactive Containers

Containers can also be used interactively for debugging or testing purposes. In this case, the container may run as long as the user keeps the interactive session open.

Example: An interactive Docker container for running a Bash shell.

FROM ubuntu:latest
CMD ["bash"]

Now build the docker image and run the container:

docker build -t interactive-container .
docker run -it interactive-container

Orchestrated Containers

Kubernetes orchestrated containers may be continuously monitored and automatically restarted if they fail or crash.

In these cases, the containers can run for a long time as they are automatically managed by the orchestrator unless interrupted externally.

Example: For this scenario, we'll use a simple web application using Node.js and Express, orchestrated using Docker Compose.

Dockerfile

FROM node:14
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "app.js"]

app.js

// app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
  res.send('Hello, World!');
});
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

docker-compose.yml

version: '3'
services:
  web:
    build: .
    ports:
      - "3000:3000"

Also Read: Kubernetes vs Docker Swarm

Daemon Containers

The last on this list are Daemon containers. Docker containers can be run as background daemons, serving a specific purpose and running as long as the system is active or until manually stopped.

Example: A simple Docker container running a monitoring tool like htop as a daemon.

Dockerfile

FROM debian:latest
RUN apt-get update && apt-get install -y htop
CMD ["htop"]

Build the image and run the container:

docker build -t daemon-container .
docker run -d --name my_daemon_container daemon-container
Note

Docker containers are not intended to be persistent storage solutions. Any data that needs to be preserved should be stored outside the container using Docker volumes or other data persistence mechanisms.

Background: Why Keep Docker Container in Running State?

There could be multiple scenarios (other than just debugging as mentioned in the title) where you would want to keep your docker container running. Let's look at a few common ones.

Application Availability

When the container is in a running state, it is ready to respond to incoming traffic immediately.

Real-time Updates

If your application requires updates or changes, you can apply them while the container is running.

Scalability

Running containers is essential for horizontal scaling.

Resource Efficiency

Avoid the overhead of frequently starting and stopping containers, which can save resources and improve performance.

Stateful Services

Some applications need to maintain stateful information, such as databases.

Service Discovery and Load Balancing

Your running containers can register themselves with service discovery tools, making it easier for other services to locate and interact with them.

Also Read: Docker vs Containerd vs Cri-o

Logging and Monitoring

Monitor the container's health, resource usage, and other performance metrics.

Fast Startup

Containers can start quickly, but avoiding the frequent restart of the same containers makes little sense.

Testing and Debugging

Devs can access the container, inspect its contents, and troubleshoot issues more effectively.

Also Read: DaemonSets in Kubernetes

How to Keep the Container Running Indefinitely?

The following are the various ways to keep running a container in the background. But, fair warning: do it so if you really need it.

Running containers do eat up some amount of CPU if you forget to exit them.

The default behavior allows each container to have unrestricted access to the host machine's CPU cycles.

However, it is possible to apply constraints to restrict a specific container's CPU access.

The majority of users prefer the default CFS scheduler, but there is an option to configure the real-time scheduler if needed.

Also Read: How to Cleanup Docker Resources?

Use -d or --detach

The most common method to keep a Docker container running is to run the container in detached mode using the -d or --detach option.

This starts the container in the background, and you will regain control of the terminal immediately.

docker run -d image_name

Use docker start after Creating the Docker Container

You can first create the container and then start it using docker start with the container ID or name.

Why this method?

It is useful when you want to stop and restart the container later.

docker create --name my_container image_name
docker start my_container

Use docker-compose

Specify the detach option in your docker-compose.yml file to keep the docker containers running in the background.

version: '3'
services:
  my_service:
    image: image_name
    # Other configuration options for the service
    # ...
    # Run the service in the background
    detach: true

Then, start the services with the following command:

docker-compose up -d

Use docker run with tail -f

Run this command in the foreground (that never exits) while keeping the docker container running.

A common practice is to use tail -f /dev/null to keep the container running without any other functionality.

docker run -d image_name tail -f /dev/null

Use docker run with sleep:

Similar to the previous method, you can use the sleep command to keep the docker container running indefinitely.

docker run -d image_name sleep infinity

Use docker run with a Long-Running Command

If your container runs a long-running process, such as a web server, database, or application, it will keep running in the background until you explicitly stop it.

docker run -d image_name command_to_run

Here's an example using the above syntax:

docker run image_name while true; do sleep 1; done

Troubleshooting: Docker Container Automatically Stops even after "docker run -d"

Let's first look at how the docker run command works.

  • By default, the container runs in the foreground unless you specifically use the -d flag to detach it.

  • The container will continue to run as long as the specified command is active, and it will stop once the command completes its execution.

Here is an example.

Let's use the nginx image to run a web server container. Use the following 'docker run' command:

docker run -d -p 8080:80 nginx

In this example, the -d flag will detach the container, and the -p flag will map port 8080 of the host to port 80 of the container. As a result, the nginx web server will be accessible on port 8080 of your machine.

After running this command, the nginx container will remain active in the background, serving web content, and will continue running as long as the web server is operational.

But, the moment you stop the web server or the nginx process inside the container, the container will automatically stop.

To verify the running containers, use the docker ps -a command.

If you already tried the above solution and still the problem persists, try the following.

Append your docker command with:

docker run -d image_name tail -f /dev/null

Or in Dockerfile:

ENTRYPOINT ["tail"] CMD ["-f","/dev/null"]

Also, adding the -it flag will prevent your container from exiting when running in the background.

You can then use:

docker exec -it image_name 

You can use -t and -i flags separately too.

As Docker documentation says combining -i and -t options will cause it to behave like a shell.

Append your command with just -t, as such:

docker run -t -d image_name you_command(optional)  

Also Read: Kubectl Exec Command Tutorial

Frequently Asked Questions

1. How do I stop a Docker container from closing?

Use the -d flag when running the container. The -d flag stands for "detached" mode, and it allows the container to run in the background.

docker run -d your_image_name

To stop the container at a later time, you can use the docker stop command, providing the container ID or name

docker stop your_container_id_or_name

2. How do I keep a Docker container running after reboot?

Use the --restart flag.

docker run -d --restart=unless-stopped your_image_name

With this configuration, the container will automatically start running when your system boots up, and it will continue running unless you explicitly stop it using the docker stop command. Other values for --restart=no/always/on-failure[:max-retries]

3. How do you run a Docker container and keep it running?

Use the docker run command without the -d flag. However, you should be aware that if you close the terminal or interrupt the process, the container will be stopped.

After using his you won't be able to interact with the container's console directly. But can view its logs or access the running container by using the docker exec command:

docker exec -it your_container_id_or_name bash
Priyansh Khodiyar's profile

Written by Priyansh Khodiyar

Priyansh is the founder of UnYAML and a software engineer with a passion for writing. He has good experience with writing and working around DevOps tools and technologies, APMs, Kubernetes APIs, etc and loves to share his knowledge with others.