How to Automatically Start Docker Containers on Ubuntu Startup

DockerDockerBeginner
Practice Now

Introduction

This tutorial will guide you through the process of automatically starting Docker containers on Ubuntu system startup. You will learn how to install Docker, understand Docker containers and images, and then configure Docker to start your containers automatically when your Ubuntu server boots up. By the end of this guide, you will be able to ensure your critical Docker-based applications are always running and available.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("`Docker`")) -.-> docker/ContainerOperationsGroup(["`Container Operations`"]) docker(("`Docker`")) -.-> docker/SystemManagementGroup(["`System Management`"]) docker/ContainerOperationsGroup -.-> docker/ps("`List Running Containers`") docker/ContainerOperationsGroup -.-> docker/run("`Run a Container`") docker/ContainerOperationsGroup -.-> docker/start("`Start Container`") docker/ContainerOperationsGroup -.-> docker/stop("`Stop Container`") docker/SystemManagementGroup -.-> docker/info("`Display System-Wide Information`") docker/SystemManagementGroup -.-> docker/version("`Show Docker Version`") docker/ContainerOperationsGroup -.-> docker/ls("`List Containers`") subgraph Lab Skills docker/ps -.-> lab-393099{{"`How to Automatically Start Docker Containers on Ubuntu Startup`"}} docker/run -.-> lab-393099{{"`How to Automatically Start Docker Containers on Ubuntu Startup`"}} docker/start -.-> lab-393099{{"`How to Automatically Start Docker Containers on Ubuntu Startup`"}} docker/stop -.-> lab-393099{{"`How to Automatically Start Docker Containers on Ubuntu Startup`"}} docker/info -.-> lab-393099{{"`How to Automatically Start Docker Containers on Ubuntu Startup`"}} docker/version -.-> lab-393099{{"`How to Automatically Start Docker Containers on Ubuntu Startup`"}} docker/ls -.-> lab-393099{{"`How to Automatically Start Docker Containers on Ubuntu Startup`"}} end

Introduction to Docker and Container Technology

Docker is a powerful platform that revolutionized the way applications are developed, packaged, and deployed. It is a containerization technology that allows developers to create, deploy, and run applications in isolated, self-contained environments called containers. Containers provide a consistent and reproducible runtime environment, ensuring that applications run the same way regardless of the underlying infrastructure.

What is Docker?

Docker is an open-source software platform that enables the creation and deployment of applications within containers. Containers are lightweight, standalone, and executable packages that include everything an application needs to run, including the code, runtime, system tools, and libraries. This approach ensures that the application will always run the same, regardless of the environment it is deployed in.

Benefits of Docker

  • Consistency: Containers provide a consistent and predictable runtime environment, ensuring that applications run the same way across different systems and platforms.
  • Scalability: Docker makes it easy to scale applications by allowing you to quickly create and deploy new containers as needed.
  • Efficiency: Containers are lightweight and use fewer resources than traditional virtual machines, making them more efficient and cost-effective to run.
  • Portability: Applications packaged as Docker containers can be easily moved and deployed across different environments, from development to production.
  • Isolation: Containers provide a high degree of isolation, ensuring that applications and their dependencies are separated from the host system and other containers.

Docker Architecture

Docker uses a client-server architecture, where the Docker client communicates with the Docker daemon (the server) to perform various operations, such as building, running, and managing containers. The Docker daemon runs on the host system and is responsible for managing the containers and their lifecycle.

graph LR A[Docker Client] -- API --> B[Docker Daemon] B -- Containers --> C[Docker Images] B -- Volumes --> D[Docker Volumes] B -- Networks --> E[Docker Networks]

Docker Containers and Images

Docker containers are the runtime instances of Docker images. An image is a read-only template that contains the application code, dependencies, and all the necessary components to run the application. When you run a Docker image, it creates a container, which is the running instance of the image.

Use Cases for Docker

Docker is widely used in various scenarios, including:

  • Microservices: Docker enables the development and deployment of microservices, where each service is packaged in a separate container.
  • Continuous Integration and Deployment: Docker simplifies the process of building, testing, and deploying applications by providing a consistent and reproducible environment.
  • Cloud and Serverless Computing: Docker containers can be easily deployed and scaled on cloud platforms and serverless environments.
  • Developer Productivity: Docker streamlines the development process by providing a consistent and isolated environment for developers to work on their applications.

By understanding the basics of Docker and container technology, you'll be well on your way to leveraging the power of Docker to streamline your application development and deployment processes.

Installing Docker on Ubuntu Linux

Prerequisites

Before installing Docker on your Ubuntu 22.04 system, ensure that you have the following prerequisites:

  • Ubuntu 22.04 (LTS) operating system
  • Sudo or root privileges to install packages

Install Docker on Ubuntu 22.04

  1. Update the package index:
sudo apt-get update
  1. Install the necessary packages to allow apt to use packages over HTTPS:
sudo apt-get install -y \
    ca-certificates \
    curl \
    gnupg \
    lsb-release
  1. Add the official Docker GPG key:
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  1. Set up the Docker repository:
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
  1. Install Docker Engine, containerd, and Docker Compose:
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
  1. Verify the Docker installation:
sudo docker run hello-world

This command downloads a test image and runs it in a container, verifying that Docker is installed and configured correctly.

Post-installation Steps

  1. Manage Docker as a non-root user:
sudo usermod -aG docker $USER

Log out and log back in for the changes to take effect.

  1. Enable Docker to start on system boot:
sudo systemctl enable docker.service
sudo systemctl enable containerd.service

Congratulations! You have successfully installed Docker on your Ubuntu 22.04 system. You can now proceed to learn about Docker containers and images.

Understanding Docker Containers and Images

Docker Containers

Docker containers are the runtime instances of Docker images. A container is a lightweight, standalone, and executable package that includes everything an application needs to run, such as the code, runtime, system tools, and libraries. Containers provide a consistent and predictable runtime environment, ensuring that applications run the same way regardless of the underlying infrastructure.

To create a new container, you can use the docker run command:

docker run -it ubuntu:22.04 /bin/bash

This command will create a new container based on the ubuntu:22.04 image and start an interactive shell session within the container.

Docker Images

A Docker image is a read-only template that contains the application code, dependencies, and all the necessary components to run the application. Images are the building blocks of containers and are used to create and deploy Docker containers.

You can create your own Docker images or use pre-built images from public or private registries, such as Docker Hub. To build a custom Docker image, you can use a Dockerfile, which is a text file that contains instructions for building the image.

Here's an example Dockerfile that creates a simple "Hello, World!" application:

FROM ubuntu:22.04
RUN apt-get update && apt-get install -y nodejs
COPY app.js /app/
WORKDIR /app
CMD ["node", "app.js"]

This Dockerfile:

  1. Starts from the ubuntu:22.04 base image
  2. Installs the Node.js runtime
  3. Copies the app.js file into the container
  4. Sets the working directory to /app
  5. Specifies the command to run the application (node app.js)

To build the image, you can use the docker build command:

docker build -t my-app .

This will create a new Docker image named my-app based on the instructions in the Dockerfile.

Interacting with Docker Containers and Images

You can use various Docker commands to manage your containers and images, such as:

  • docker run: Create and start a new container
  • docker ps: List running containers
  • docker stop: Stop a running container
  • docker rm: Remove a container
  • docker build: Build a new image from a Dockerfile
  • docker push: Push an image to a registry
  • docker pull: Pull an image from a registry

By understanding the concepts of Docker containers and images, you'll be able to leverage the power of containerization to streamline your application development and deployment processes.

Configuring Docker to Start Containers Automatically

Understanding Docker Startup Options

Docker provides several options to configure the automatic startup of containers. The two main approaches are:

  1. Using Docker Compose: Docker Compose is a tool for defining and running multi-container Docker applications. You can configure Docker Compose to start containers automatically when the system boots up.

  2. Using systemd: systemd is the default init system and service manager for many Linux distributions, including Ubuntu 22.04. You can use systemd to start Docker containers automatically on system startup.

In this section, we'll focus on the systemd-based approach, as it provides more flexibility and control over the startup process.

Using systemd to Start Docker Containers on System Startup

  1. Create a systemd service file:
    Create a new file named my-docker-container.service in the /etc/systemd/system/ directory:
sudo nano /etc/systemd/system/my-docker-container.service
  1. Configure the service file:
    Add the following content to the file, replacing the placeholders with your specific container details:
[Unit]
Description=My Docker Container
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker run --name my-container -d my-image:latest
ExecStop=/usr/bin/docker stop my-container

[Install]
WantedBy=multi-user.target
  1. Reload systemd and start the service:
sudo systemctl daemon-reload
sudo systemctl start my-docker-container.service
  1. Enable the service to start on system boot:
sudo systemctl enable my-docker-container.service

Now, whenever your Ubuntu 22.04 system boots up, the my-docker-container.service will automatically start the specified Docker container.

Verifying the Automatic Startup

You can use the following commands to check the status of the service and the running container:

sudo systemctl status my-docker-container.service
docker ps

By configuring Docker containers to start automatically using systemd, you can ensure that your applications are always running and available, even after system reboots or power outages.

Using systemd to Start Docker Containers on System Startup

Understanding systemd

systemd is the default init system and service manager for many Linux distributions, including Ubuntu 22.04. It is responsible for managing the startup and shutdown of system services, including Docker containers.

Creating a systemd Service File

To configure Docker containers to start automatically on system startup, you need to create a systemd service file. This file defines the service and its startup behavior.

  1. Create a new service file:
sudo nano /etc/systemd/system/my-docker-container.service
  1. Add the following content to the file, replacing the placeholders with your specific container details:
[Unit]
Description=My Docker Container
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker run --name my-container -d my-image:latest
ExecStop=/usr/bin/docker stop my-container

[Install]
WantedBy=multi-user.target

Here's what each section of the service file does:

  • [Unit]: Defines the service dependencies and the order in which the service should start.
  • [Service]: Configures the service behavior, including the command to start and stop the container.
  • [Install]: Specifies when the service should be started (in this case, when the system enters the "multi-user" target).

Enabling and Starting the Service

After creating the service file, you need to reload the systemd daemon and start the service.

  1. Reload the systemd daemon:
sudo systemctl daemon-reload
  1. Start the service:
sudo systemctl start my-docker-container.service
  1. Enable the service to start on system boot:
sudo systemctl enable my-docker-container.service

Verifying the Automatic Startup

You can use the following commands to check the status of the service and the running container:

sudo systemctl status my-docker-container.service
docker ps

By configuring Docker containers to start automatically using systemd, you can ensure that your applications are always running and available, even after system reboots or power outages.

Practical Examples and Use Cases

Automatically Starting a Web Server Container

Let's consider a practical example of automatically starting a web server container on system startup. We'll use the popular Nginx web server as an example.

  1. Create a systemd service file for the Nginx container:
sudo nano /etc/systemd/system/nginx-container.service
  1. Add the following content to the file:
[Unit]
Description=Nginx Container
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker run --name nginx -p 80:80 -d nginx:latest
ExecStop=/usr/bin/docker stop nginx

[Install]
WantedBy=multi-user.target
  1. Reload the systemd daemon and start the service:
sudo systemctl daemon-reload
sudo systemctl start nginx-container.service
sudo systemctl enable nginx-container.service

Now, whenever your Ubuntu 22.04 system boots up, the Nginx web server container will automatically start and be accessible on port 80.

Automatically Starting a Database Container

Another common use case is automatically starting a database container, such as MongoDB or PostgreSQL, on system startup. The process is similar to the web server example:

  1. Create a systemd service file for the database container:
sudo nano /etc/systemd/system/database-container.service
  1. Add the following content to the file, replacing the placeholders with your specific container details:
[Unit]
Description=Database Container
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker run --name database -d my-database-image:latest
ExecStop=/usr/bin/docker stop database

[Install]
WantedBy=multi-user.target
  1. Reload the systemd daemon and start the service:
sudo systemctl daemon-reload
sudo systemctl start database-container.service
sudo systemctl enable database-container.service

By automatically starting your database and web server containers, you can ensure that your LabEx applications are always available and ready to serve your users.

Summary

In this comprehensive tutorial, you have learned how to automatically start Docker containers on Ubuntu system startup. By configuring Docker and using systemd, you can ensure your Docker-based applications are up and running when your Ubuntu server boots up, providing a reliable and efficient way to manage your containerized infrastructure.

Other Docker Tutorials you may like