Docker Containers in Depth – Part 5

Let’s jump into practical directly.

Let’s run a container from image ubuntu.

docker run --name my_ubu ubuntu:latest

It should ideally run a container. However, it is showing me the container in the exited state.

This is because docker run will run a command /bin/bash on the container(available in snippet). This command is present in the image. Different images can have different commands. To execute a /bin/bash command, you should be attached to it. Here in the example no shell is being provided. If you don’t attach to a shell, a shell gets exited.

To attach to a shell we can provide an option of -it

docker run -it ubuntu:latest /bin/bash

where

i => interactive
t => tty session/shell

This command will create a container, execute /bin/bash command on it and attaches to the shell using -it. This would look like that you have logged in to a container.

Let’s run a command on a container

As we can see that /bin/bash is having the PID as 1. If this process is dead, then the container is dead.

What happens when we type “exit” on a shell ? It terminates. Similarly, once I am attached to a container as above a type exit, the container will be dead. If I want to detach myself from the container and make sure that the container is still running, press Ctrl+p+q.

Running commands from host machine on a container

Using docker exec command you can execute any command on a container from outside. This is mostly used for troubleshooting.

Attach to a container

docker attach {container name/id}

Golden Rules to work with Containers

  • Don’t make changes to a container
  • What if you want to make change ? We REPLACE a container with a new container built from a new Image
  • One container == One Service
  • Containers can connect to each other via IP address. However, we prefer to connect containers together via their names as IP’s are not reliable as they can change w.r.t environment and we delete and create containers and their IP’s change.

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts