Docker: Launching a Container from an Image


The docker run command is used to launch Docker containers from images.
In this article, I’ll show you how to launch a container from an image using the example of the last official Ubuntu official Docker image.
I will show how to install apache2 inside a container with Ubuntu and how to save this container as a new image.
And in the end I will show how to start containers from this new image in the interactive and background modes.

Launching a Container from an Image in Docker

Do Not Confuse:

Docker image itself cannot be “launched”. The docker run command takes the Docker image as a template and creates a container from it that launches.

Find the required image on the Docker Hub:

$ docker search ubuntu
NAME                            DESCRIPTION             STARS  OFFICIAL  AUTOMATED
ubuntu                          Ubuntu is a Debian...   6759   [OK]       
dorowu/ubuntu-desktop-lxde-vnc  Ubuntu with openss...   141              [OK]
rastasheep/ubuntu-sshd          Dockerized SSH ser...   114              [OK]
ansible/ubuntu14.04-ansible     Ubuntu 14.04 LTS w...   88               [OK]
ubuntu-upstart                  Upstart is an even...   80     [OK]

Download the Docker image from the repository using the docker pull command:

$ docker pull ubuntu

Launch the container from the Docker image:

$ docker run -it ubuntu /bin/bash

When you run docker run IMAGE, the Docker engine takes IMAGE, adds a writable top layer and initializes various parameters (network ports, container name, identifier and resource limits).

Install apache2 web server inside the container, and then exit it :

root@e485d06f2182:/# apt update
root@e485d06f2182:/# apt install apache2 -y
root@e485d06f2182:/# exit

From the stopped container in which you installed apache2, create a new image and name it apache_snapshot:

$ docker commit e485d06f2182 apache_snapshot

To view all the images on the Docker host, do:

$ docker images
REPOSITORY          TAG           IMAGE ID            CREATED             SIZE
apache_snapshot     latest        13037686eac3        22 seconds ago      249MB
ubuntu              latest        00fd29ccc6f1        3 weeks ago         111MB

Now, from the new Docker image, you can run containers interactively:

$ docker run -it apache_snapshot /bin/bash

Or, from this Docker image, you can run the container in the background with the port: 80 inside the Docker container forwarded to port: 8080 of the Docker host:

$ docker run -d -p 8080:80 apache_snapshot /usr/sbin/apache2ctl -D FOREGROUND

In this case, to make sure that apache2 inside the container is running, just open http://localhost:8080/ and you will see the start page: “Apache2 Ubuntu Default Page”.

Similar Posts:


How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Scroll to Top