How To Install and Use Docker on Ubuntu 18.04

Introduction

The main mission of Docker as an application is to simplify managing application processes in containers, which help running your applications in resource-isolated processes. Containers can be compared to virtual machines; however, they are more resource-friendly, more portable, and more dependent on the host operating system.

To get a more detailed discussion of the different Docker components, see The Docker Ecosystem: An Introduction to Common Components.

This tutorial will guide you upon the installation and use of Docker Community Edition (CE) on Ubuntu 18.04. We will guideyou upon Docker installation process, as well as working with images and containers, and pushing an image to a Docker Repository.

For this tutorial, you need:

  • One Ubuntu 18.04 server, a sudo non-root user and a firewall.
  • An account on Docker Hub. It is needed if you plan to create your own images and push them to Docker Hub.

Step One  — Docker Installation Process

The official Ubuntu repository may not necessarily contain the latest version of Docker installation package. To get the latest version, you need to install Docker from the official Docker repository. To download the application from the website, add a new package source. You will need the Docker GPG key to ensure the downloads are valid, as well as to install the package.

The first thing you should do is to update your existing list of packages:

# sudo apt update

After that, you need to install some prerequisite packages that let apt use packages over HTTPS. To do that, type:

# sudo apt install apt-transport-https ca-certificates curl software-properties-common

Then proceed with adding the GPG key for the official Docker repository to the system:

# curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

After that, add the Docker repository to APT sources:

# sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"

The next step is to update the package database with the Docker packages taken from the repo you have just added:

# sudo apt update

Be attentive to  install from the Docker repo but not the default Debian repo:

# apt-cache policy docker-ce

Normally, you will see the output as shown below, yet the version number for Docker may be different:

Output of apt-cache policy docker-ce
docker-ce:
  Installed: (none)
  Candidate: 18.03.1~ce~3-0~ubuntu
  Version table:
     18.03.1~ce~3-0~ubuntu 500
        500 https://download.docker.com/linux/ubuntu bionic/stable amd64 Packages

As you can see, docker-ce was not installed, but bionic stands as the candidate for installation from the Docker repository for Ubuntu 18.04.

The final step is to install Docker:

# sudo apt install docker-ce

At this moment, Docker is installed, the daemon started, and the process is enabled to start on boot. To check that the application is running, type:

# sudo systemctl status docker

You are supposed to see the output similar to the one shown below. If you see something alike, it means that the service is active and running:

Output
● docker.service - Docker Application Container Engine
   Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2018-06-04 14:07:37 UTC; 1min 45s ago
     Docs: https://docs.docker.com
 Main PID: 10097 (dockerd)
    Tasks: 16
   CGroup: /system.slice/docker.service
           ├─10097 /usr/bin/dockerd -H fd://
           └─10114 docker-containerd --config /var/run/docker/containerd/containerd.toml

Having installed Docker, you receive the Docker service (daemon) and the Docker client (docker command line utility). Further in this tutorial,  you will be guided on how to use the docker command.

Step Two  — Executing the Docker Command Without Sudo (Optional)

Only the root user or a user in the docker group can run the docker command. The user is created automatically during the process of Docker installation. If you try to run the docker command without the sudo prefix and not in the docker group, you will receive the following output:

Output
docker: Cannot connect to the Docker daemon. Is the docker daemon running on this host?.
See 'docker run --help'.

If you do not want to add sudo every time you run the docker command, type your username to the docker group:

# sudo usermod -aG docker ${USER}

You need to log out of the server and log in again in order to to apply the new group membership. An alternative way is to type the following command:

# su - ${USER}

The system will prompt you to enter your user’s password to continue.

To confirm that the user has been added to the docker group, type the following:

# id -nG
Output
sammy sudo docker

In case you need to add another user (which you have not logged in as) to the docker group, state its username explicitly:

# sudo usermod -aG docker username

The below guide is based on the supposition that you run the docker command as a user in the docker group. In case you prefer not to, prepend the commands with sudo.

Step Three — The Docker Command

The use of docker command consists of passing it a chain of commands and options followed by arguments. The syntax looks like this:

# docker [option] [command] [arguments]

To see the subcommands available, type:

# docker

Concerning Docker 18, the list of available subcommands looks like this:

Output

  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

To check the options available to a particular command, enter:

# docker docker-subcommand --help

To get Docker system-wide information, type:

# docker info

To get an understanding of some of these commands, check the information below. Let us start with images.

Step Four  — Working with Docker Images

Docker images build Docker containersDocker is set by default to pull these images from Docker Hub. It is a Docker registry that is managed by Docker company.  Any person can host Docker images on Docker Hub. It means that Linux distributions as well as most applications you might be using, will have images hosted there.

In order to check access and the ability to download images from Docker Hub, type the comand below:

# docker run hello-world

If you see the output below , it is an indication of Docker correct work:

Output
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
9bb5a5d4561a: Pull complete
Digest: sha256:3e1764d0f546ceac4565547df2ac4907fe46f007ea229fd7ef2718514bcec35d
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.
...

Initially, Docker was unable to find the hello-world image locally. That is why it downloaded the image from the default repository Docker Hub. Having downloaded the image, Docker created a container from the image and the application within the container executed, displaying the message.

Use the docker command and the search subcommand to look for images available on Docker Hub. For instance, to search for the Ubuntu image, type the command below:

# docker search ubuntu

The script will crawl Docker Hub and offer a list of all images that match the search string. You should see the output alike:

Output
NAME                                                      DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
ubuntu                                                    Ubuntu is a Debian-based Linux operating sys…   7918                [OK]
dorowu/ubuntu-desktop-lxde-vnc                            Ubuntu with openssh-server and NoVNC            194                                     [OK]
rastasheep/ubuntu-sshd                                    Dockerized SSH service, built on top of offi…   157                                     [OK]
ansible/ubuntu14.04-ansible                               Ubuntu 14.04 LTS with ansible                   93                                      [OK]
ubuntu-upstart                                            Upstart is an event-based replacement for th…   88                  [OK]
neurodebian                                               NeuroDebian provides neuroscience research s…   51                  [OK]
ubuntu-debootstrap                                        debootstrap --variant=minbase --components=m…   38                  [OK]
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5      ubuntu-16-nginx-php-phpmyadmin-mysql-5          37                                      [OK]
nuagebec/ubuntu                                           Simple always updated Ubuntu docker images w…   24                                      [OK]
tutum/ubuntu                                              Simple Ubuntu docker images with SSH access     19
i386/ubuntu                                               Ubuntu is a Debian-based Linux operating sys…   14
ppc64le/ubuntu                                            Ubuntu is a Debian-based Linux operating sys…   13
1and1internet/ubuntu-16-apache-php-7.0                    ubuntu-16-apache-php-7.0                        10                                      [OK]
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mariadb-10   ubuntu-16-nginx-php-phpmyadmin-mariadb-10       7                                       [OK]
eclipse/ubuntu_jdk8                                       Ubuntu, JDK8, Maven 3, git, curl, nmap, mc, …   7                                       [OK]
codenvy/ubuntu_jdk8                                       Ubuntu, JDK8, Maven 3, git, curl, nmap, mc, …   5                                       [OK]
darksheer/ubuntu                                          Base Ubuntu Image -- Updated hourly             5                                       [OK]
1and1internet/ubuntu-16-apache                            ubuntu-16-apache                                4                                       [OK]
1and1internet/ubuntu-16-nginx-php-5.6-wordpress-4         ubuntu-16-nginx-php-5.6-wordpress-4             4                                       [OK]
1and1internet/ubuntu-16-sshd                              ubuntu-16-sshd                                  2                                       [OK]
pivotaldata/ubuntu                                        A quick freshening-up of the base Ubuntu doc…   2
1and1internet/ubuntu-16-healthcheck                       ubuntu-16-healthcheck                           0                                       [OK]
pivotaldata/ubuntu-gpdb-dev                               Ubuntu images for GPDB development              0
smartentry/ubuntu                                         ubuntu with smartentry                          0                                       [OK]
ossobv/ubuntu
...

As you can see, in the OFFICIAL column, OK stands for an image built and supported by the company behind the project. When you identify the image you want  to use, use the pull subcommand to download it to your computer.

The following command will download the official ubuntu image to your computer:

# docker pull ubuntu

The following output will be returned:

Output
Using default tag: latest
latest: Pulling from library/ubuntu
7b98dfc16071: Pull complete
5001a1209541: Pull complete
7319fc68c576: Pull complete
b24603670dc3: Pull complete
98f170c87c6f: Pull complete
Digest: sha256:6f4bdc3467537cbbe663e80db2c4ec95d548a9145d64453b06939c4592d67b6d
Status: Downloaded newer image for ubuntu:latest

After the download, use the run subcommand run to run a container using the downloaded image. Same as in the hello-world example, if an image has not been downloaded while executing docker with the run subcommand, the first thing that the Docker client will do is download the image, and after that, run a container using it.

Type the command provided below to see the downloaded images:

# docker images

The output will look like the following:

Output
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              213a43faa138        3 weeks ago         81.3MB
hello-world         latest              e48bc07ac18e        1 months ago        1.86kB

As shown later in this tutorial, you can modify images used to run containers. Moreover, you can use them to generate new images, which you can upload (push in technical language) to Docker Hub or other Docker registries.

Step Five — How to Run a Docker Container

The container hello-world is an example of a container which runs and exits having emitted a test message. However, containers can be interactive and more useful. As mentioned before, they are like virtual machines, yet more resource-friendly.

See the example of how to run a container with the latest Ubuntu image. You can get interactive shell access into the container by using the combination of the -i and -t switches:

# docker run -it ubuntu

Your command prompt should take the form shown below. This way, it will reflect the fact that you work inside the container:

Output
root@d9b200f2f636:/#

Pay attention to the container id reflected in the command prompt. Remeber it. In our example, the id is d9b100f2f636. This ID will be needed later to identify the container when you need to remove it.

Now any command can be run inside the container. As an example, you can update the package database inside the container. What is notable, there is no need to use sudo prefix because you operate inside the container as the root user:

root@d9b200f2f631:/# apt update

After that install any application inside it. As an example, we install Node.js:

root@d9b200f2f631:/# apt install nodejs

This command will install Node.js from the official Ubuntu repository in the container. After the installation, check the installation status of Node.js:

root@d9b200f2f631:/# node -v

Your terminal will return the version number:

Output
v8.10.0

Please note thay any alteration made inside the container applies only to that container.

If you need to exit the container, simply type exit at the prompt.

To learn how to manage the containers on our system, see the below sections.

Step Six — How to Manage Docker Containers

In the process of use, many active (running) and inactive containers will be stored on your computer. To see those that are active, type:

# docker ps

Normally, you should see a similar output:

Output
CONTAINER ID        IMAGE               COMMAND             CREATED             

In our tutorial, two containers have been started; the first from the hello-world image and the second one from the ubuntu image. None of them is running; however, they  exist in  your system.

To check all containers both active and inactive, use docker ps with the -a switch:

# docker ps -a

Normally, you should see a similar output:

d9b200f2f636        ubuntu              "/bin/bash"         About an hour ago   Exited (0) 7 minutes ago                           sharp_volhard
02c950718166        hello-world         "/hello"            About an hour ago   Exited (0) About an hour ago                       festive_williams

To see the container that was created the last, pass it the -l switch:

# docker ps -l
# CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
# d9b200f2f636        ubuntu              "/bin/bash"         About an hour ago   Exited (0) 10 minutes ago                       sharp_volhard

Use docker start to start a stopped container. The command should be followed by the container’s name or the container ID. See how to start the Ubuntu-based container with the ID d9b100f2f636:

# docker start d9b200f2f636

This way, you will start the container. View its status with docker ps:

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
d9b200f2f636        ubuntu              "/bin/bash"         About an hour ago   Up 7 seconds                            sharp_volhard

Type docker stop and follow it by the container name or ID.  In our example, we will apply the name that was assigned to the container by Docker, which is sharp_volhard:

# docker stop sharp_volhard

If you do not need a container anymore, use the docker rm command to remove it. Remember to follow it with the container name or ID. The docker ps -a command will help you find the container ID or name for the container associated with the hello-world image.

# docker rm festive_williams

To can start a new container and name it, use the --name switchYou can create a container that will be self-removed when stopped. For that, use the --rm switch. To get additional information, use the docker run help command.

You can turn containers into images that can be used to build new containers. See the following section.

Step Seven — Making Changes in a Container to a Docker Image

In a Docker image, you can make different manipulations such as creating, modifying, and deleting files exactly as you can do with a virtual machine. What is noteworthy is that the changes made inside the image will only apply to that container. You can start and stop it, but if you use the docker rm command, you will destroy it along with the changes made.

In this section, you will learn how to save the state of a container as a new Docker image.

Having installed Node.js in the Ubuntu container, your container runs off an image. However, this container differs from the image that was used to create it. You can reuse this Node.js container as the basis for new images later.

Then use the command provided below to implement the changes to a new Docker image instance:

# docker commit -m "What you did to the image" -a "Author Name" container_id repository/new_image_name

The -m switch stands for the commit message, which informs about the changes made, and -a  specifies the author. The container_id is the one that was noted earlier when starting the interactive Docker session. If you have not created additional repositories on Docker Hub, the repository will be your Docker Hub username.

For Instance, for the user sammy, which has the container ID d9b100f2f636, you should use the command:

# docker commit -m "added Node.js" -a "sammy" d9b200f2f636 sammy/ubuntu-nodejs

When you commit an image, it is saved on your computer locally. The tutorial will show you how to push an image to a Docker registry like Docker Hub to provide access to it to others.

Type the command below to see the listing of the Docker images. It will show the new and those from which they derived:

# docker images

The output like below will be returned:

Output
REPOSITORY               TAG                 IMAGE ID            CREATED             SIZE
sammy/ubuntu-nodejs   latest              8c1f35226ca6        6 seconds ago       178MB
ubuntu                   latest              213a43faa138        3 weeks ago         81.3MB
hello-world              latest              e48bc07ac18e        1 months ago        1.86kB

As you can see from the example, ubuntu-nodejs is the new image. It was derived from the ubuntu image that already existed at Docker Hub . The size difference shows the changes made. In this case, the change means the installation of NodeJS. Therefore, if you need to run a container using Ubuntu with NodeJS pre-installed, use the new image.

Also, you can build Images from a Dockerfile. It helps to automate software installation in a new image. This tutorial does not cover this question.

See the section below to find out how to make the image available to others.

Step Eight — Pushing Docker Images to a Docker Repository

To share the created image with others,namely to push an image to Docker Hub or any other registry of Docker, you must have an account there.

First of all, log into Docker Hub to be able to push your image:

# docker login -u docker-registry-username

After that, you will see the prompt that will ask you to authenticate with your Docker Hub password. With the correct password in place, authentication will succeed.

Important: If your Docker registry username differs from the local username that was used to create the image, tag your image with your registry username. Based on data in the example discussed in the previous section, type:

# docker tag sammy/ubuntu-nodejs docker-registry-username/ubuntu-nodejs

Then use the command below to push your own image:

# docker push docker-registry-username/docker-image-name

In order to push the ubuntu-nodejs image to the sammy repository, type the following command:

# docker push sammy/ubuntu-nodejs

You might need to wait until  it uploads the images, and return the output like this:

Output
The push refers to a repository [docker.io/sammy/ubuntu-nodejs]
e4fbbfb44187: Pushed
6f70bf18a086: Pushed
a4b5c80a4eba: Pushed
8f18b442972b: Pushed
4ce512daaf78: Pushed
8aae4540b42d: Pushed

...

 An image that was pushed to a registry, should be listed on the dashboard of your account. It should look like the image below.

New Docker image listing on Docker Hub

If a push attempt returns an error like this, you might not have logged in:

Output
The push refers to a repository [docker.io/sammy/ubuntu-nodejs]
e4fbbfb44187: Preparing
6f70bf18a086: Preparing
a4b5c80a4eba: Preparing
8f18b442972b: Preparing
4ce512daaf78: Preparing
8aae4540b42d: Waiting
unauthorized: authentication required

Thus, you need to log in using docker login and try to push the image again. After that, check if it exists on your Docker Hub repository page.

From now on, docker pull sammy/ubuntu-nodejs command will pull the image to a new machine. The image will be used to run a new container.

 

 

 

 

  • DOCKER, UBUNTU 18.04
  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 18.04

Introduction ‘LAMP” is a stack of open-source software. Typically, it is installed together in...

How To Install Linux, Nginx, MySQL, PHP (LEMP stack) on Ubuntu 18.04

Introduction LEMP is a pack of software. It is generally used to serve dynamic web applications...

How To Install Nginx on CentOS 7

What is Nginx Nginx is server software that is characterized by high performance, flexibility,...

How To Install Node.js on Debian 10

Introduction Node.js a Javascript platform that allows easy creation of networked applications...

How To Install Node.js on Ubuntu 18.04

Introduction Node.js is a JavaScript platform that is used to allow users to build network...