×
☰ See All Chapters

docker run command to start an interactive bash session

While running the docker, sometime you need to execute commands inside the container. As an example if you are running application with linux base image then you may have to check the application logs form inside the container linux OS. Now you should execute commands inside the container. In other words, you should get a command prompt to be able to issue typical Linux commands.

Docker allows you to execute commands inside the container while it is still running when you run docker in interactive mode. By using the container interactively, you can access a command prompt inside the running container. Below is the syntax to run container in interactive mode.

docker run -it IMAGE[:TAG|@DIGEST] /bin/bash

Below is an example of docker run in interactive mode. We have used spring boot application running in interactive mode. When you run a sprintboot application in interactive mode you will be initially landed to springboot application console, all the commands you enter inside the container are forwarded to sprinboot server not to linux OS.  You can execute commands to linux and see what's going on inside the container by jumping on a shell inside the container using docker exec in interactive mode (docker exec -it [CONTAINER_ID] /bin/sh).

docker-interactive-bash-session-exec-0
 
docker-interactive-bash-session-exec-1
 

How do I SSH into a running container

Using docker exec command you can connect to a container that is already running. When you are running docker in a detached mode and to get a command prompt to be able to issue typical Linux commands you can run docker exec command in interactive mode. Follow the below syntax to SSH (secure shell) into a running container.

docker exec -it <containername> /bin/bash

OR

docker exec -it <containerid> /bin/bash

docker-interactive-bash-session-exec-2
 

The meaning behind -it flag

The –it flag is a combination of -i and –t flag. In other words, the Docker exec command can also be written as below.

docker exec –i -t <containername> /bin/bash

OR

docker exec –i -t <containerid> /bin/bash

docker-interactive-bash-session-exec-3
 

A running container has a STDIN, STDOUT and STDERR communication channel. The -i flag is for STDIN and the -t flag is for STDOUT and STDERR. Anything you type in your host machine’s terminal is passed to the STDIN channel of the container. The output from the container, if any, is sent back to the terminal using the STDOUT channel in case of proper execution. However, in case of error the STDERR channel is used.


All Chapters
Author