How to Install Docker on Ubuntu

Install Docker on Ubuntu

Docker has become an essential tool for modern developers and system administrators, revolutionizing how applications are built, shipped, and deployed. If you’re running Ubuntu and looking to harness the power of containerization, you’ve come to the right place. This comprehensive guide will walk you through every step of installing Docker on Ubuntu, from preparation to post-installation configuration and beyond.

According to recent statistics, over 65% of organizations are now using Docker in production environments, with Ubuntu being one of the most popular host operating systems. Let’s dive into how you can join the containerization revolution with a proper Docker setup on your Ubuntu system.

Table of Contents

Understanding Docker Basics

What is Docker and Why Use It?

Docker is an open-source platform that automates the deployment of applications inside lightweight, portable containers. These containers package up an application with all of its dependencies, libraries, and configuration files, ensuring it runs the same regardless of the environment.

Unlike traditional applications that run directly on your operating system, Docker containers are isolated but share the host system’s kernel, making them incredibly efficient. A typical Docker container starts in milliseconds and uses a fraction of the resources compared to virtual machines.

Here’s why Docker has become so popular:

  • Consistency: Eliminates the “it works on my machine” problem by ensuring applications run the same everywhere
  • Isolation: Keeps applications and their dependencies separate from each other
  • Resource efficiency: Uses host system resources more effectively than traditional virtualization
  • Speed: Containers start nearly instantly and can be created/destroyed rapidly
  • Scalability: Makes it easy to scale applications horizontally by spinning up multiple identical containers

For Ubuntu users, Docker provides a streamlined way to run multiple applications with different requirements without conflicts or compatibility issues.

Docker vs Traditional Virtualization

While Docker might seem similar to virtual machines at first glance, there are fundamental differences that make Docker more efficient in many scenarios:

Feature Docker Containers Virtual Machines
Startup time Seconds Minutes
Resource usage Lightweight Heavy (needs full OS)
Isolation level Process isolation Hardware-level isolation
Size Megabytes Gigabytes
Portability Highly portable Less portable

On Ubuntu, Docker containers run natively with minimal overhead, using the host kernel directly. This architecture gives you near-native performance while maintaining excellent isolation between applications.

Docker Architecture Overview

Before installing Docker, it’s helpful to understand its architecture:

  1. Docker Engine: The core of Docker, consisting of:
    • Docker daemon (dockerd): A background service managing containers
    • REST API: Provides interface for programs to talk to the daemon
    • CLI client: The docker command you’ll use to interact with Docker
  2. Docker objects:
    • Images: Read-only templates containing application code and dependencies
    • Containers: Runnable instances of images
    • Volumes: Persistent data storage for containers
    • Networks: Communication channels between containers
  3. Docker Registry: Storage for Docker images (Docker Hub is the public registry)

On Ubuntu, all these components work seamlessly together to provide a robust containerization platform.

System Requirements for Docker on Ubuntu

Hardware Requirements

Docker is relatively lightweight, but to run it efficiently on Ubuntu, your system should meet these minimum requirements:

  • 64-bit processor with virtualization support (Intel VT-x or AMD-V)
  • 2 GB RAM (4+ GB recommended for running multiple containers)
  • 20 GB free disk space (more for storing images and container data)

For development environments, these specifications are usually sufficient. Production environments may require more resources depending on your workload.

According to performance benchmarks, Docker on Ubuntu can run efficiently even on modest hardware. A test by DigitalOcean showed that even a 1GB RAM server could run several small containers simultaneously with proper configuration.

Supported Ubuntu Versions

Docker is compatible with the following Ubuntu versions:

  • Ubuntu 22.04 LTS (Jammy Jellyfish)
  • Ubuntu 20.04 LTS (Focal Fossa)
  • Ubuntu 18.04 LTS (Bionic Beaver)
  • Ubuntu 16.04 LTS (Xenial Xerus) – limited support

For optimal compatibility and security, using the latest LTS (Long-Term Support) version of Ubuntu is recommended. As of writing, Ubuntu 22.04 LTS offers the best Docker experience with the latest kernel improvements for container technology.

Docker’s official documentation states that using an LTS release ensures stability and security updates for both the host OS and Docker itself, making it ideal for production environments.

Required User Permissions

To install and manage Docker on Ubuntu, you’ll need:

  • Sudo privileges or root access
  • User in the ‘sudo’ group
  • Internet connectivity for downloading packages

Without these permissions, you won’t be able to install Docker system-wide or manage it effectively. Docker requires elevated privileges because it interacts directly with system resources, networking stacks, and kernel features.

Preparing Your Ubuntu System

Updating Your System

Before installing Docker, it’s crucial to update your Ubuntu system to ensure all packages are current:

sudo apt update
sudo apt upgrade -y

This process might take a few minutes depending on your internet connection and how many packages need updating. A fully updated system minimizes compatibility issues and security vulnerabilities.

A recent survey of Docker installations found that 23% of failed Docker installations were due to outdated system packages, making this step crucial for success.

Removing Old Docker Versions

If you’ve previously installed Docker, it’s important to remove old versions to prevent conflicts:

sudo apt remove docker docker-engine docker.io containerd runc

Don’t worry if you see a message that these packages aren’t installed-that just means you don’t have any old versions to remove.

The Docker packages may have changed names over time, so this command ensures all legacy versions are removed. This clean slate approach prevents conflicts between different Docker versions that might cause stability issues.

Installing Required Dependencies

Setting Up Package Management Tools

Docker requires several package management tools that might not be installed by default on minimal Ubuntu installations:

sudo apt install apt-transport-https ca-certificates curl software-properties-common

These packages enable Ubuntu’s package manager (APT) to use repositories over HTTPS, which is required for Docker’s official repository.

Installing SSL Certificates

Docker’s repository uses HTTPS for secure downloads, so certificate management tools are essential:

sudo apt install gnupg lsb-release

These packages help verify the authenticity of the Docker packages you’ll download, protecting your system from potentially compromised software. Security experts recommend always verifying software signatures, especially for infrastructure components like Docker.

Installing Docker on Ubuntu

Method 1: Using the Official Docker Repository

This is the recommended method for most users as it makes updating Docker easier in the future.

Adding Docker’s GPG Key

First, add Docker’s official GPG key to ensure package authenticity:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

This command downloads Docker’s GPG key and adds it to your system’s keyring, allowing APT to verify that packages from Docker’s repository are authentic and haven’t been tampered with.

Setting Up the Repository

Next, add Docker’s official repository to your APT sources:

echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

This command automatically detects your Ubuntu version and architecture to add the appropriate repository. The $(lsb_release -cs) portion extracts your Ubuntu codename (like “jammy” for 22.04 or “focal” for 20.04) to ensure you get packages compatible with your system.

Installing Docker Engine

With the repository configured, update your package index:

sudo apt update

Now install Docker Engine, the CLI, and related tools:

sudo apt install docker-ce docker-ce-cli containerd.io docker-compose-plugin docker-buildx-plugin

This installs the following components:

  • docker-ce: The Docker Engine (Community Edition)
  • docker-ce-cli: Command-line interface for Docker
  • containerd.io: The container runtime Docker uses
  • docker-compose-plugin: For defining multi-container applications
  • docker-buildx-plugin: Extended build capabilities

Installation typically takes 2-3 minutes depending on your internet speed and system performance. Once complete, Docker will start automatically.

Method 2: Using the Convenience Script

For testing and development environments, Docker provides a convenience script that automates the installation process.

Script Functionality and Considerations

The convenience script handles all the repository setup and installation steps automatically. While convenient, this method gives you less control over the specific components installed and should generally be avoided in production environments.

Docker’s official documentation notes that the script is regularly updated but may install the latest (potentially unstable) versions of Docker. For production systems, the repository method is generally preferred for predictability.

Running the Installation Script

To use the convenience script:

curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

The script will detect your operating system, add the appropriate repositories, and install Docker. The output will show you each step of the process as it progresses.

According to community benchmarks, this method is approximately 40% faster than the manual repository setup but offers less customization.

Method 3: Manual Installation with DEB Package

For air-gapped environments or systems with limited internet access, you can manually download and install Docker packages.

First, visit the Docker download page and download the required DEB packages for your Ubuntu version:

  • https://download.docker.com/linux/ubuntu/dists/

Navigate to your Ubuntu version’s directory, then to the pool/stable/ directory for your architecture (usually amd64). Download these packages:

  • docker-ce
  • docker-ce-cli
  • containerd.io
  • docker-buildx-plugin
  • docker-compose-plugin

Install them using:

sudo dpkg -i ./docker-ce_*.deb ./docker-ce-cli_*.deb ./containerd.io_*.deb ./docker-buildx-plugin_*.deb ./docker-compose-plugin_*.deb

If you see dependency errors, resolve them with:

sudo apt install -f

This method is more involved but necessary for systems without direct internet access or with strict security policies.

Post-Installation Configuration

Running Docker Without Sudo

By default, only the root user or users with sudo privileges can run Docker commands. To allow non-root users to run Docker commands:

sudo usermod -aG docker $USER

This adds your current user to the ‘docker’ group. Log out and back in for the changes to take effect, or run:

newgrp docker

This configuration change is recommended for development environments but should be considered carefully for production systems since it effectively grants root-equivalent permissions for Docker operations.

A security study showed that 62% of Docker-related security incidents involve improper permission configurations, so consider your security requirements carefully.

Configuring Docker to Start on Boot

Ensure Docker starts automatically when your Ubuntu system boots:

sudo systemctl enable docker.service
sudo systemctl enable containerd.service

Verify the service is running:

sudo systemctl status docker

You should see output indicating the service is “active (running)”. This configuration ensures Docker is always available after system reboots, which is especially important for production environments.

Testing Your Docker Installation

Verify your installation by running the hello-world container:

docker run hello-world

If successful, you’ll see a message confirming Docker is working properly. This test container performs several actions:

  1. The Docker client contacts the Docker daemon
  2. The daemon pulls the “hello-world” image from Docker Hub
  3. The daemon creates a container from the image and runs it
  4. The container outputs the test message and exits

If all these steps complete successfully, your Docker installation is working correctly.

Managing Docker on Ubuntu

Basic Docker Commands

Now that Docker is installed, get familiar with these essential commands:

  • View Docker information:
    docker info
    docker version
  • List containers:
    docker ps          # Running containers
    docker ps -a       # All containers, including stopped ones
  • List images:
    docker images
  • Pull an image:
    docker pull ubuntu:22.04
  • Start an interactive container:
    docker run -it ubuntu:22.04 bash
  • Stop and remove containers:
    docker stop container_id
    docker rm container_id
  • Remove images:
    docker rmi image_id

These commands form the foundation of Docker usage. According to usage statistics, these 7 commands account for over 80% of daily Docker operations for most users.

Working with Docker Images

Docker images are the blueprints for containers. Here’s how to manage them effectively:

  1. Searching for images on Docker Hub:
    docker search nginx
  2. Pulling specific image versions using tags:
    docker pull nginx:1.23
  3. Building your own image from a Dockerfile:
    docker build -t my-app:1.0 .
  4. Viewing image details:
    docker inspect image_name
  5. Saving and loading images for transfer between systems:
    docker save -o my-image.tar my-image:1.0
    docker load -i my-image.tar

Docker Hub, the default public registry, hosts over 12 million images with billions of pulls per month, showing the vast ecosystem available to Ubuntu Docker users.

Creating and Managing Containers

Containers are running instances of Docker images. Here’s how to work with them:

  1. Running a container in the background:
    docker run -d --name web -p 8080:80 nginx

    This runs an Nginx container named “web” with port 8080 on your host mapped to port 80 in the container.

  2. Executing commands in a running container:
    docker exec -it web bash
  3. Viewing container logs:
    docker logs web
  4. Stopping, starting, and restarting containers:
    docker stop web
    docker start web
    docker restart web
  5. Setting resource limits:
    docker run -d --name limited-container --cpus="0.5" --memory="512m" nginx

Container management is where Docker’s flexibility shines on Ubuntu. You can easily run dozens of isolated applications without the overhead of traditional virtualization.

Docker Best Practices for Ubuntu

Security Considerations

Securing your Docker installation on Ubuntu should be a priority:

  1. Keep Docker updated:
    sudo apt update
    sudo apt install docker-ce docker-ce-cli containerd.io
  2. Run containers with least privilege:
    docker run --user 1000:1000 --cap-drop=ALL my-app
  3. Scan images for vulnerabilities:
    docker scout cves nginx:latest
  4. Use official images from trusted publishers
  5. Implement network segmentation with Docker networks:
    docker network create --driver bridge isolated_network
    docker run --network=isolated_network my-app

A 2023 container security report found that 76% of Docker containers in production have at least one high or critical vulnerability, highlighting the importance of security best practices.

Performance Optimization

Optimize Docker’s performance on your Ubuntu system:

  1. Use the overlay2 storage driver (default in newer versions):
    {
      "storage-driver": "overlay2"
    }

    Add this to /etc/docker/daemon.json if needed.

  2. Limit logging to prevent disk space issues:
    docker run --log-driver=json-file --log-opt max-size=10m --log-opt max-file=3 nginx
  3. Regularly clean unused resources:
    docker system prune -a
  4. Use multi-stage builds to create smaller images:
    FROM node:16 AS build
    WORKDIR /app
    COPY . .
    RUN npm ci && npm run build
    
    FROM nginx:alpine
    COPY --from=build /app/dist /usr/share/nginx/html
  5. Optimize CPU and memory allocation based on workload requirements

Performance testing shows that properly optimized Docker containers on Ubuntu can achieve within 95-98% of bare-metal performance for most applications.

Resource Management

Manage Docker’s resource usage on your Ubuntu system:

  1. Set global limits in /etc/docker/daemon.json:
    {
      "default-shm-size": "64M",
      "default-ulimits": {
        "nofile": {
          "Name": "nofile",
          "Hard": 64000,
          "Soft": 64000
        }
      }
    }
  2. Monitor resource usage:
    docker stats
  3. Implement disk quotas for container storage
  4. Use cgroups v2 for better resource control (available on Ubuntu 22.04+)
  5. Restart policies for container availability:
    docker run --restart=unless-stopped nginx

Proper resource management ensures Docker containers don’t adversely affect your Ubuntu system’s stability or performance, especially important in production environments.

Troubleshooting Common Issues

Permission Problems

Permission issues are among the most common Docker problems on Ubuntu:

  1. Socket permission denied:
    Got permission denied while trying to connect to the Docker daemon socket

    Solution: Add your user to the docker group:

    sudo usermod -aG docker $USER
    newgrp docker
  2. Permission issues with mounted volumes:Solution: Match user IDs or use named volumes:
    docker run -v $(pwd):/app --user $(id -u):$(id -g) my-app
  3. Can’t access files created by containers:Solution: Set appropriate file permissions in Dockerfile:
    RUN chown -R user:user /app

According to Docker community forums, permission issues account for approximately 35% of all support requests from Ubuntu users.

Network Configuration Issues

Network problems can be tricky to diagnose:

  1. Container can’t connect to the internet:Solution: Check Docker’s DNS settings:
    docker run --dns 8.8.8.8 ping google.com
  2. Port binding failures:
    Error starting userland proxy: listen tcp4 0.0.0.0:80: bind: address already in use

    Solution: Choose a different port or stop the service using the conflicting port:

    sudo lsof -i :80
  3. Container-to-container communication issues:Solution: Create a custom bridge network:
    docker network create my_network
    docker run --network=my_network --name container1 image1
    docker run --network=my_network --name container2 image2

Network issues often stem from firewall configurations or port conflicts on Ubuntu systems. Using netstat and ufw status commands can help diagnose these problems.

Storage and Disk Space Management

Docker can consume significant disk space over time:

  1. System running out of disk space:Solution: Clean up unused Docker resources:
    docker system prune -a --volumes
  2. Container running out of storage:Solution: Mount a volume with sufficient space:
    docker run -v /path/with/space:/container/path my-app
  3. Slow performance due to storage driver:Solution: Switch to overlay2 if not already using it:
    # In /etc/docker/daemon.json:
    {
      "storage-driver": "overlay2"
    }

A study of Docker deployments found that unmanaged Docker storage is the leading cause of production outages in containerized environments, with the average deployment accumulating 5-15GB of unused images per month.

Advanced Docker Configuration

Docker Compose Installation and Setup

Docker Compose simplifies managing multi-container applications:

  1. Install Docker Compose (if not installed with the compose plugin):
    sudo apt update
    sudo apt install docker-compose-plugin
  2. Verify installation:
    docker compose version
  3. Create a sample docker-compose.yml:
    version: '3'
    services:
      web:
        image: nginx
        ports:
          - "8080:80"
      db:
        image: mysql:8.0
        environment:
          MYSQL_ROOT_PASSWORD: example
          MYSQL_DATABASE: app
        volumes:
          - db-data:/var/lib/mysql
    volumes:
      db-data:
  4. Start services:
    docker compose up -d

Docker Compose is used in over 80% of Docker development workflows, according to GitHub repository statistics, making it an essential tool for Ubuntu Docker users.

Working with Docker Volumes

Volumes are the preferred way to persist data in Docker:

  1. Create a named volume:
    docker volume create my_data
  2. Mount a volume to a container:
    docker run -v my_data:/app/data nginx
  3. Inspect volume details:
    docker volume inspect my_data
  4. Back up a volume:
    docker run --rm -v my_data:/source -v $(pwd):/backup ubuntu tar czvf /backup/my_data.tar.gz -C /source .
  5. Restore a volume:
    docker run --rm -v my_data:/target -v $(pwd):/backup ubuntu bash -c "cd /target && tar xzvf /backup/my_data.tar.gz"

Volumes solve many persistence issues with Docker containers and are especially important for database containers where data must survive container restarts.

Custom Network Configuration

Advanced networking features in Docker:

  1. Create a custom bridge network:
    docker network create --driver bridge --subnet=172.20.0.0/16 custom_network
  2. Connect existing containers to networks:
    docker network connect custom_network container_name
  3. Using the host network (shares host’s network namespace):
    docker run --network host nginx
  4. Creating a macvlan network (containers appear as physical devices on your network):
    docker network create -d macvlan \
      --subnet=192.168.1.0/24 \
      --gateway=192.168.1.1 \
      -o parent=eth0 macvlan_network
  5. Setting static IPs for containers:
    docker run --network custom_network --ip 172.20.0.10 nginx

Custom networking is crucial for more complex Docker deployments on Ubuntu, especially in production environments with specific network topology requirements.

FAQs About Installing Docker on Ubuntu

Does installing Docker on Ubuntu affect system performance?

Yes, but minimally for most users. Docker uses containerization technology that’s more lightweight than traditional virtualization. On idle systems, Docker typically consumes less than 100MB of RAM and negligible CPU. However, each running container adds resource consumption based on its workload. For most Ubuntu desktop or server installations with moderate specifications, you won’t notice performance degradation unless running many containers simultaneously. To optimize performance, consider using resource limits for containers and regular system maintenance.

Can I install Docker on Ubuntu running in WSL2 on Windows?

Yes, Docker runs well on Ubuntu in WSL2. Microsoft has specifically optimized WSL2 to support Docker workloads. Install Docker on your Ubuntu WSL2 instance using the standard repository method described in this article. Alternatively, you can install Docker Desktop for Windows which integrates with WSL2 automatically. Performance is nearly identical to native Linux installations, though file I/O might be slightly slower when accessing Windows file systems mounted in WSL2. For best performance, keep your Docker files within the Linux filesystem.

How do I update Docker after installation on Ubuntu?

Updating Docker is straightforward using standard Ubuntu package management. Run sudo apt update to refresh package information, then sudo apt install docker-ce docker-ce-cli containerd.io to update to the latest versions. Docker services typically restart automatically after updates. For production systems, review the release notes before updating as breaking changes may occur between versions. If you installed via the convenience script, rerunning the script will update your installation. Always backup important container data before major version updates.

What’s the difference between Docker CE and Docker EE on Ubuntu?

Docker CE (Community Edition) is free and open-source, while Docker EE (Enterprise Edition) was the commercial offering with additional features. However, Docker EE has been discontinued and replaced by Docker Business, Docker Team, and Docker Personal subscriptions. On Ubuntu, most users should install Docker CE, which provides all core containerization features. Enterprise users can use Docker CE with additional Docker subscription services for enhanced security scanning, management features, and support. The installation process for Docker CE described in this guide is appropriate for most use cases.

Why is Docker showing “Cannot connect to the Docker daemon” errors on my Ubuntu system?

This error typically indicates the Docker daemon isn’t running or you lack permissions to access it. First, check if the Docker service is active with sudo systemctl status docker. If it’s not running, start it with sudo systemctl start docker. If the service is running but you still see this error, you likely have permission issues. Either prefix Docker commands with sudo or add your user to the docker group with sudo usermod -aG docker $USER and then log out and back in. Other causes might include firewall settings blocking socket connections or corruption in Docker’s configuration files. In rare cases, reinstalling Docker completely resolves persistent daemon connection issues.

Marshall Anthony is a professional Linux DevOps writer with a passion for technology and innovation. With over 8 years of experience in the industry, he has become a go-to expert for anyone looking to learn more about Linux.

Related Posts