In this blog post, we’ll look at how to get on a Docker container running in the background. It will also cover how to into a docker container that was started and left running in the background without an active console session.

Docker adoption has been tremendous, especially in the world of microservices and development. Most Docker containers running for long periods of time don’t have active shell console. You’ll likely connect to bash shell on demand, i.e when you want to run some commands on the terminal.  An alternative to this will be ssh to the container using an IP address.

1) Using docker exec

Docker engine has a command line tool docker which is used to interact with containers. The command option exec is used to run a command in a running container. By passing some parameters, we should be able to get bash session. The command syntax used is:


Below is a list of options which can be used with this.

-d, –detach Detached mode: run command in the background
-i, –interactive Keep STDIN open even if not attached
-t, –tty Allocate a pseudo-TTY
-u, –user string Username or UID (format: <name|uid>[:<group|gid>])
-w, –workdir string Working directory inside the container

Our interest is on the options -t and -i since bash has to run in an interactive mode. Let’s consider an example to make this clear.

Pull   Docker image:

# docker pull nginx 
Using default tag: latestlatest: Pulling from library/nginx
f2aa67a397c4: Pull complete 3c091c23e29d: Pull complete 4a99993b8636: Pull complete 
Digest: sha256:0edf702c890e9518b95b2da01286509cd437eb994b8d22460e40d72f6b79be49Status: 
Downloaded newer image for nginx:latest

Start a test container in the background based on downloaded docker image.

# docker run --name nginx-bg -d nginx 

This will start a container named nginx-bg in the background from nginx docker imageCheck to confirm that the container is running:

# docker ps

Now run the following command to get bash console on this container.

# docker exec -it nginx-bg /bin/bash
[email protected]:/# apt-get update
Get:2 stretch/updates InRelease [94.3 kB]
Ign:1 stretch InRelease 
Get:3 stretch-updates InRelease [91.0 kB]
Hit:4 stretch Release
Fetched 185 kB in 2s (83.4 kB/s) 
Reading package lists... Done

where nginx-bg  is container name and /bin/bash is the path to bash binary on the container. Once done executing commands on bash shell, you can exit by typing exit command.

[email protected]:/# exit

2) Using docker attach command

An alternative method to docker exec is docker attach. Syntax is

# docker attach <container-name>

So in our case, we’ll run:

# docker attach nginx-bg

This should drop you into bash shell by default.

ssh into a running container

If you want to ssh to a running Docker container, you need container IP address or hostname configured on /etc/hosts or valid record in your network.

If you don’t know the IP address of the container, you can get it using the command below:

export INSTANCE_NAME="nginx-bg"
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $INSTANCE_NAME


# export INSTANCE_NAME="nginx-bg"
# docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $INSTANCE_NAME

Note that you can replace container name with its ID. We got the IP address to be, try ping it to see if responsive.

# ping -c 2

PING ( 56(84) bytes of data.
64 bytes from icmp_seq=1 ttl=64 time=0.107 ms
64 bytes from icmp_seq=2 ttl=64 time=0.058 ms
--- ping statistics ---2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.058/0.082/0.107/0.026 ms

You need to have configured ssh on the container prior to running ssh command to it. Once configured, you can ssh to it using username and container’s IP Address.

# ssh [email protected] 
[email protected]'s : 
Linux 672175da3a51 3.10.0-693.17.1.el7.x86_64 #1 SMP Thu Jan 25 20:13:58 UTC 2018 x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr//doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
[email protected]:~#

Passwordless SSH between containers

If you need passwordless authentication, consider copying your SSH public key to the container when running it. I don’t recommend creating an image with the public key on it, but rather having the file on the host system that has all public keys authorized.

Let’s create a file:

# mkdir ~/container-ssh-keys
#   ~/container-ssh-keys/authorized_keys
# chmod 0600 ~/container-ssh-keys/authorized_keys

Then add your public SSH key to the file, you can add as many as you want. Now when starting the container, map this file to /root/.ssh/authorized_keys on the container, e.g

# docker run --name mycon -it -v $HOME/container-ssh-keys/authorized_keys:/root/.ssh/authorized_keys \
ubuntu:16.04 /bin/bash

You should then be able to ssh from your host system with the private key pair for the copied public key without being prompted for the password.

# ssh [email protected]

Another Way SSH into a Container

How do I SSH into a running container

There is a docker exec command that can be used to connect to a container that is already running.

  • Use docker ps to get the name of the existing container
  • Use the command docker exec -it <container name> /bin/bash to get a bash shell in the container
  • Generically, use docker exec -it <container name> <command> to execute whatever command you specify in the container.

How do I run a command in my container?

The proper way to run a command in a container is: docker-compose run <container name> <command>. For example, to get a shell into your web container you might run docker-compose run web /bin/bash

To run a series of commands, you must wrap them in a single command using a shell. For example: docker-compose run
<name in yml> sh -c '<command 1> && <command 2> && <command 3>'

In some cases you may want to run a container that is not defined by a docker-compose.yml file, for example to test a new container configuration. Use docker run to start a new container with a given image: docker run -it <image name> <command>

The docker run command accepts command line options to specify volume mounts, environment variables, the working directory, and more.

Getting a shell for build/tooling operations

Getting a shell into a build container to execute any operations is the simplest approach. You simply want to get access to the cli container we defined in the compose file. The command docker-compose -f build.yml run cli will start an instance of the phase2/devtools-build image and run a bash shell for you. From there you are free to use drushgrunt or whatever your little heart desires.

Running commands, but not from a dedicated shell

Another concept in the Docker world is starting a container to run a single command and allowing the container stop when the command is completed. This is great if you run commands infrequently, or don’t want to have another container constantly running. Running your commands on containers in this fashion is also well suited for commands that don’t generate any files on the filesystem or if they do, they write those files on to volumes mounted into the container.

The drush container defined in the example build.yml file is a container designed specifically to run drush in a single working directory taking only the commands as arguments. This approach allows us to provide a quick and easy mechanism for running any drush command, such as sqlccache-rebuild, and others, in your Drupal site quick and easily.

There are also other examples of a grunt command container similar to drush and an even more specific command container around running a single command, drush make to build the site from a make/dependency file.

Print Friendly, PDF & Email



Bài viết liên quan