How to Run Docker Containers and Return to Command Line

DockerDockerBeginner
Practice Now

Introduction

This tutorial will guide you through the process of running Docker containers and returning to the command line without stopping the container. You'll learn how to install and configure Docker, run containers, and manage them effectively. By the end of this tutorial, you'll have the knowledge to seamlessly integrate Docker into your development workflow.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("`Docker`")) -.-> docker/ContainerOperationsGroup(["`Container Operations`"]) docker/ContainerOperationsGroup -.-> docker/ps("`List Running Containers`") docker/ContainerOperationsGroup -.-> docker/restart("`Restart Container`") docker/ContainerOperationsGroup -.-> docker/run("`Run a Container`") docker/ContainerOperationsGroup -.-> docker/start("`Start Container`") docker/ContainerOperationsGroup -.-> docker/stop("`Stop Container`") docker/ContainerOperationsGroup -.-> docker/ls("`List Containers`") subgraph Lab Skills docker/ps -.-> lab-392886{{"`How to Run Docker Containers and Return to Command Line`"}} docker/restart -.-> lab-392886{{"`How to Run Docker Containers and Return to Command Line`"}} docker/run -.-> lab-392886{{"`How to Run Docker Containers and Return to Command Line`"}} docker/start -.-> lab-392886{{"`How to Run Docker Containers and Return to Command Line`"}} docker/stop -.-> lab-392886{{"`How to Run Docker Containers and Return to Command Line`"}} docker/ls -.-> lab-392886{{"`How to Run Docker Containers and Return to Command Line`"}} end

Introduction to Docker

Docker is a popular open-source platform that enables developers to build, deploy, and run applications in a containerized environment. Containers are lightweight, standalone, and self-contained units that package an application and its dependencies, ensuring consistent and reliable execution across different computing environments.

What is Docker?

Docker is a software platform that allows you to build, deploy, and run applications in containers. Containers are a way to package an application and all its dependencies into a single, portable unit that can run consistently on any environment. This includes the application code, runtime, system tools, and system libraries - everything needed to run the application.

Benefits of Using Docker

  1. Consistency: Docker containers ensure that an application will run the same way, regardless of the underlying infrastructure.
  2. Scalability: Docker makes it easy to scale applications up or down, depending on the workload.
  3. Efficiency: Containers are lightweight and share the host operating system, making them more efficient than traditional virtual machines.
  4. Portability: Docker containers can run on any machine that has Docker installed, making it easy to move applications between different environments.
  5. Isolation: Each Docker container is isolated from the others, providing a secure and reliable environment for running applications.

Docker Architecture

Docker uses a client-server architecture, where the Docker client communicates with the Docker daemon, which is responsible for building, running, and managing Docker containers. The Docker daemon runs on the host machine, while the client can run on the same machine or a remote machine.

graph LD subgraph Docker Architecture Client --> Daemon Daemon --> Images Daemon --> Containers end

Getting Started with Docker

To get started with Docker, you'll need to install the Docker engine on your machine. You can download and install Docker from the official Docker website (https://www.docker.com/get-started). Once installed, you can use the docker command-line tool to interact with the Docker daemon and manage your containers.

Here's an example of how to run a simple "Hello, World!" container using Docker:

docker run hello-world

This command will pull the hello-world image from the Docker Hub registry, create a new container, and run the hello-world application inside the container. The output will show a message confirming that the container was successfully run.

Installing and Configuring Docker

Installing Docker on Ubuntu 22.04

To install Docker on Ubuntu 22.04, follow these steps:

  1. Update the package index:

    sudo apt-get update
  2. Install the necessary packages to allow apt to use a repository over HTTPS:

    sudo apt-get install \
      ca-certificates \
      curl \
      gnupg \
      lsb-release
  3. 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
  4. 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
  5. Install Docker Engine, containerd, and Docker Compose:

    sudo apt-get update
    sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin
  6. Verify the installation by running the hello-world container:

    sudo docker run hello-world

Configuring Docker

After installing Docker, you can configure it to suit your needs. Here are some common configuration options:

Manage Docker as a non-root user

By default, the docker command can only be run by the root user. To allow non-root users to run Docker, you can add them to the docker group:

sudo usermod -aG docker $USER

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

Set Docker daemon options

You can customize the Docker daemon options by editing the /etc/docker/daemon.json file. For example, to change the default storage driver:

{
  "storage-driver": "overlay2"
}

After making changes, restart the Docker daemon:

sudo systemctl restart docker

Configure Docker Compose

Docker Compose is a tool for defining and running multi-container Docker applications. You can configure Docker Compose by creating a docker-compose.yml file in your project directory.

Here's an example docker-compose.yml file:

version: "3"
services:
  web:
    image: nginx:latest
    ports:
      - "80:80"
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: password

This configuration defines two services: a web server running Nginx and a MySQL database.

Running Docker Containers

Starting a Docker Container

To start a Docker container, you can use the docker run command. The basic syntax is:

docker run [options] image [command] [args]

Here's an example of running a Ubuntu container and executing the echo command inside it:

docker run ubuntu echo "Hello, LabEx!"

This command will pull the ubuntu image from the Docker Hub registry, create a new container, and execute the echo "Hello, LabEx!" command inside the container.

Interacting with Docker Containers

You can interact with a running Docker container using the following commands:

  • docker ps: List all running containers
  • docker exec: Execute a command inside a running container
  • docker logs: View the logs of a container
  • docker stop: Stop a running container
  • docker start: Start a stopped container
  • docker rm: Remove a container

For example, to execute a bash shell inside a running container:

docker exec -it ubuntu bash

The -it options attach the terminal to the container's standard input and output.

Exposing Ports

If your application running inside a Docker container needs to be accessible from the host machine or the internet, you need to expose the container's ports. You can do this using the -p or --publish option when running the docker run command:

docker run -p 8080:80 nginx

This will map the container's port 80 to the host's port 8080, allowing you to access the Nginx web server running in the container from http://localhost:8080.

Managing Container Volumes

Docker containers are designed to be ephemeral, meaning that any data stored inside the container will be lost when the container is stopped or removed. To persist data, you can use Docker volumes. Volumes are a way to mount a directory from the host machine into the container.

docker run -v /path/on/host:/path/in/container image

This will mount the /path/on/host directory on the host machine to the /path/in/container directory inside the container.

Managing Docker Containers

Listing Docker Containers

To list all running Docker containers, you can use the docker ps command:

docker ps

This will display a table with information about the running containers, including the container ID, the image used, the command being executed, the creation time, the status, and the ports.

To list all containers, including stopped ones, you can use the docker ps -a command:

docker ps -a

Stopping and Starting Containers

To stop a running container, you can use the docker stop command followed by the container ID or name:

docker stop container_id

To start a stopped container, you can use the docker start command:

docker start container_id

Removing Containers

To remove a container, you can use the docker rm command:

docker rm container_id

This will remove the container, but not the image it was created from.

Inspecting Containers

To get detailed information about a container, you can use the docker inspect command:

docker inspect container_id

This will output a JSON object with information about the container, including its configuration, network settings, and more.

Monitoring Containers

To monitor the resource usage and performance of a container, you can use the docker stats command:

docker stats container_id

This will display a live stream of CPU, memory, network, and I/O usage for the specified container.

Managing Container Logs

To view the logs of a container, you can use the docker logs command:

docker logs container_id

This will display the standard output and standard error logs of the container.

Tagging and Pushing Images

Once you have built a Docker image, you can tag it with a name and push it to a registry, such as Docker Hub, so that others can use it.

## Tag the image
docker tag image_name:tag username/image_name:tag

## Push the image to Docker Hub
docker push username/image_name:tag

This allows you to share your custom Docker images with others or use them in different environments.

Detaching and Returning to Command Line

When you run a Docker container, the container's output is typically displayed in the terminal where you ran the docker run command. This can be useful for debugging and monitoring the container, but it can also be inconvenient if you need to continue using the terminal for other tasks.

Detaching from a Container

To detach from a running container and return to the command line, you can use the Ctrl+P Ctrl+Q key combination. This will detach you from the container, but the container will continue to run in the background.

Alternatively, you can start a container in detached mode by using the -d or --detach option when running the docker run command:

docker run -d image

This will start the container in the background and return you to the command line.

Reattaching to a Container

To reattach to a detached container, you can use the docker attach command:

docker attach container_id

This will reattach your terminal to the container's standard input and output, allowing you to interact with the container again.

Executing Commands in a Detached Container

Even if a container is running in detached mode, you can still execute commands inside the container using the docker exec command:

docker exec -it container_id command

The -it options attach the terminal to the container's standard input and output, allowing you to interact with the command being executed.

For example, to start a bash shell inside a detached container:

docker exec -it container_id bash

This allows you to perform additional tasks or troubleshoot the container without having to reattach to it.

Stopping a Detached Container

To stop a detached container, you can use the docker stop command:

docker stop container_id

This will gracefully stop the container, allowing it to perform any necessary cleanup tasks before exiting.

Summary

In this tutorial, you've learned how to run Docker containers and return to the command line without stopping the container. You've covered the essential steps to install and configure Docker, run containers, and manage them effectively. With this knowledge, you can now confidently integrate Docker into your development process and streamline your workflow.

Other Docker Tutorials you may like