Attach and Detach From a Docker Container: A Complete Guide

Estimated reading time: 7 minutes

Last updated on November 8th, 2024 at 04:55 pm

Docker containers run in background mode and sometimes you want to check the application logs and perform debugging. You can check How to keep the Docker container running for debugging.

Let’s learn the best Docker command to attach and detach from a Docker container with different options and ways to detach from a session without stopping the container.

Introduction Attach and Detach From a Docker Container

When we run the Docker container, it runs in foreground mode when you don’t pass any extra options.

When a Docker container is running in the background it means it’s running in Detached mode, in other words, no input/output stream is attached to the container.

Interactive mode lets you attach terminal input and output to the running container process.

Docker provides different ways to run the container, most of the time we run the Docker container in the background mode.

Attach and detach from a Docker container effectively checks the output and error of the running container.

Level Up Your DevOps Skills! 📈

Get Weekly Tips, Tutorials & Master the Latest Trends – Subscribe Now!

Subscribe Now!

Attach and Detach From a Docker Container Options:

Let’s check different options to run a container in attached or detached mode.

#1. Default / Foreground Mode:

When you run the Docker container without passing any options, it runs in Default Mode / Foreground Mode. This is the default behavior for the Docker.

Running in Foreground mode, You can’t return to the main shell prompt until the process ( Docker Container ) is over.

Bash
docker run --name foreground_mode_nginx nginx

Running the above command starts the Nginx Docker container and attaches the standard output (stdout), and the standard error (stderr) to your terminal.

Attach and Detach From a Docker Container - Default

You can see the Nginx Docker container output directly in your terminal.

You can also select the specific stream you want from stdin. In Docker CLI, you can pass the extra option -a with the stream you want

Bash
docker run --name foreground_mode_nginx -a STDERR nginx

Passing -a STDERR option only prints the error messing stream from the container.

Output TypeStandard StreamsDocker Option for “-a”
Standard OutputstdoutSTDOUT
Standard ErrorstderrSTDERR
Docker CLI extra option for a specific stream

#2. Interactive Mode

You can run the Docker container in interactive mode by, passing the -it Docker CLI option:

Bash
docker run -it --name interactive_mode_nginx nginx bash

Here, the option -it will allow you to attach the pseudo-tty.

  • -i option attach the standard input stream stdin of the bash shell
  • -t option starts the pseudo-tty terminal
Attach and Detach From a Docker Container - Interactive

You can interact with the Nginx Docker container directly from the terminal.

#3. Detached Mode

You can run the Docker container in detached mode directly by, passing -d Docker CLI option:

Bash
docker run -d --name detached_mode_nginx nginx

Here the option -d will allow you to run the Docker container in background mode directly.

Being an expert, I suggest running the Docker container in the background more for production.

Running the Docker container in the background allows us to work on other things since the terminal is not occupied with the container.

Attach and Detach From a Docker Container - background

After running the Docker container it prints the container ID and releases it.

Don’t worry you can attach it again to the same container using the container ID or name.

Fast-Track Your DevOps Career 🚀

Stay ahead of the curve with the latest industry insights. Get weekly tips & propel your skills to the next level.

Subscribe Now!

How to Interact With a Running Container

If your Docker container is already running, you might think how can you interact with the running container?

Docker CLI provides an easy-to-use way to either execute a command or attach an interactive session. Let’s check both options in detail.

#1. Attach a Session

You can attach to an already running Docker container by using docker attach:

Bash
docker attach detached_mode_nginx

Run the above command to attach terminal standard input, output, and error using the container’s ID or name.

You can only check the output and error message from the output using the --no-stdin Docker CLI option:

Bash
docker attach --no-stdin detached_mode_nginx

This will not attach STDIN

#2. Execute a Command

You can execute commands inside an already-running container by using docker exec:

Bash
docker exec -it detached_mode_nginx bash

This starts a new shell session in the container.

Run exec on a paused container

You can’t run the docker exec on the paused container. If you try to run the docker exec, it will fail with an error:

Bash
# Pause the Container
docker pause detached_mode_nginx
detached_mode_nginx


# Verify the running container
docker ps
CONTAINER ID   IMAGE     COMMAND     CREATED          STATUS                   PORTS     NAMES
382efdf29fbs   nginx    "/bin/bash"   17 seconds ago   Up 22 seconds (Paused)             detached_mode_nginx


# exec to container
docker exec detached_mode_nginx bash
Error response from daemon: Container detached_mode_nginx is paused, unpause the container before exec

#3. Docker Debug ( Beta )

Docker Debug is a CLI command that follows best practices for creating a debug shell on a slim image.

Docker Debug is still in beta and not recommended for use in production environments. Docker Debug is not available in the community version but needs a Pro, Team, or Business subscription.

Docker debug provides the Linux tools pre-installed, vim, nano, htop, and curl

Bash
docker debug detached_mode_nginx

You can inspect the filesystem with the debug shell:

Bash
docker > ls
dev  etc  nix  proc  sys

How to Detach From a Docker Container

Let’s check the way to detach from a Docker container based on running mode.

#1. Default / Foreground Mode:

You can press CTRL-C to detach the current session, but when we run the Docker container in default mode, we didn’t pass the Docker CLI option -d or -it.

Due to this, pressing the CTRL-C command stops the running container instead of detaching from it.

SIGINT signal the Docker container to kill the main process, hence stopping the container. You can check why the Docker container stops when the main process exits.

You can override the behaviors with an extra option -sig-proxy

Bash
docker run --name foreground_mode_nginx --sig-proxy=false nginx

You can press CTRL-C now to detach the current session, this will not stop the Docker container and keep it running in the background.

Detach Command: CTRL-C

#2. Interactive Mode

Since we’re already in interactive mode If you run the CTRL-C command, it will run in the interactive session. To detach the session, you need to detach a key other than CTRL-C.

Detach Command: CTRL-P or CTRL-Q

#3. Background Mode

You can pass the similar option as Foreground Mode while attaching the session --sig-proxy

Bash
docker attach background_mode_nginx --sig-proxy=false nginx

Detach Command: CTRL-C

Level Up Your DevOps Skills! 📈

Get Weekly Tips, Tutorials & Master the Latest Trends – Subscribe Now!

Subscribe Now!

How to Override the Detach Sequence?

You can override the detach sequence by passing the –detach-keys Docker CLI Option.

Bash
docker attach background_mode_nginx --detach-keys="ctrl-x"  nginx

You don’t necessarily need this option, but if the Docker default sequence conflicts with your application container, you can override this behavior.

There are two ways to change the default detach sequence:

  1. Override Per-Container Basis – Individual Override ( --detach-keys="<your_sequence>")
  2. Override the configuration for CLI in config.json

Conclusion

In conclusion, attaching and detaching from a Docker container is a simple process, whether you prefer default/foreground mode, interactive mode, or detached mode.

Don’t forget to prioritize security by checking the Docker Security Checklist to make Docker images faster, safe,r and secure.

Speed up your Docker build time x39 faster

Kashyap Merai

Kashyap Merai

Kashyap Merai, a Certified Solution Architect and Public Cloud Specialist with over 7 years in IT. He helped startups in Real Estate, Media Streaming, and On-Demand industries launch successful public cloud projects.

Passionate about Space, Science, and Computers, He also mentors aspiring cloud engineers, shaping the industry's future.

Connect with him on LinkedIn to stay updated on cloud innovations.