How To Install and Use Docker on Ubuntu 20.04


Docker is an open platform for developing, shipping, and running applications that use OS-level virtualization to deliver software in packages called containers Containers. Once deployed, use shares the host operating system resources. This means they are much more efficient than hypervisors (virtual machines) in system resource terms. Instead of virtualizing hardware, containers rest on top of a single Linux instance.

In the following tutorial, you will learn how to install and use Docker on your Ubuntu 20.04 operating system.

Prerequisites

  • Recommended OS: Ubuntu 20.04 – optional (Ubuntu 21.04)
  • User account: A user account with sudo or root access.
  • Required Packages: curl

Updating Operating System

Update your Ubuntu 20.04 operating system to make sure all existing packages are up to date:

sudo apt update && sudo apt upgrade

Install Required Packages

To successfully install Docker, you will need to install the following packages; run this command if you are unsure; it will not harm your system.

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

Install Docker

Import GPG Key and Repository

The first step in the installation of Docker is to import the GPG key with the following command:

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

Example output if successful:

OK

Next, import the repository to your APT source list as follows:

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

Now refresh your APT repository list to reflect the new repository addition:

sudo apt update

Install Docker

With the GPG key and repository imported, you can now proceed to install Docker using the following command:

sudo apt install docker-ce

Example output:

How To Install and Use Docker on Ubuntu 20.04

Type Y, then press the ENTER BUTTON to proceed with the installation.

Next, confirm the installation by checking the version/build as follows:

docker -v

Example output:

Docker version 20.10.8, build 3967b7d

An alternative is to use the apt-cache policy:

sudo apt-cache policy docker-ce

Example output:

Now, by default, the service for Docker should be automatically started on Ubuntu 20.04. To verify this, use the systemctl status command to check:

systemctl status docker

Example output:

If by some chance Docker has not been activated, use the following command to start the service:

sudo systemctl start docker

To enable Docker to start on system boot, use the following command:

sudo systemctl enable docker

Some other useful systemctl commands to know for Docker:

Restart Docker:

sudo systemctl restart docker

Stop Docker:

sudo systemctl stop docker

Disable Docker from autostart on system boot:

sudo systemctl disable docker

Optional – Add a user to Docker Group

By default, Docker can only be used with root and sudo commands. For most users, especially those that are the only users on the operating system, it is not a big deal, but if you would do away with the extra commands, you need to add your username to the Docker group.

Example:

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

To avoid this, and avoid using root or sudo command, add your username to Docker to its usergroup. To do this, use the following command:

sudo usermod -aG docker ${USER}

Next, to apply the change, you will need to log out and log back in. To do this, use the following command:

su - ${USER}

Now, you should confirm that your user is added to the docker group by typing:

id -nG

Example output:

joshua sudo docker

Alternatively, to add another user to the docker group, you can do so using the following command:

sudo usermod -aG docker username

How to use Docker

How to use Commands

To use Docker, you will need to learn the options and commands. An example of how this looks:

sudo docker [option] [command]

Now, a good starting point is to view all available commands:

Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default
                           "/home/joshua/.docker")
  -c, --context string     Name of the context to use to connect to the
                           daemon (overrides DOCKER_HOST env var and
                           default context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level
                           ("debug"|"info"|"warn"|"error"|"fatal")
                           (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default
                           "/home/joshua/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default
                           "/home/joshua/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default
                           "/home/joshua/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  app*        Docker App (Docker Inc., v0.9.1-beta3)
  builder     Manage builds
  buildx*     Build with BuildKit (Docker Inc., v0.6.1-docker)
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  scan*       Docker Scan (Docker Inc., v0.8.0)
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  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 view more information about a command, use the following command to display more information.

sudo docker <command> --help

For example, the tutorial will display help information about the push command in docker:

To view system-wide information about docker on your system, use the following command:

sudo docker info

Example output:

Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Build with BuildKit (Docker Inc., v0.6.1-docker)
  scan: Docker Scan (Docker Inc., v0.8.0)

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 0
 Server Version: 20.10.8
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: e25210fe30a0a703442421b0f60afac609f950a3
 runc version: v1.0.1-0-g4144b63
 init version: de40ad0
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.11.0-34-generic
 Operating System: Ubuntu 20.04.3 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 3.81GiB
 Name: ubuntu
 ID: CLA2:OOBD:5BJW:4WPT:4Y7L:ZGS6:VNIL:JGV4:ZTUA:IG3S:BGX7:Z626
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

How to test Docker Images are accessible

To understand how Docker works, Docker containers are built from Docker images pulled from Docker Hub that is owned and maintained by the company that created Docker. Docker Hub allows anyone to host their Docker image, so most applications and Linux distributions are hosted on the Hub.

The first test is to make sure Docker Hub is accessible, and you can download images from the Docker Hub. To do this, use the following command:

sudo docker run hello-world

Now, the first thing you may notice is the output “Unable to find image ‘hello-world:latest’ locally.” Do not worry; this is normal, and depending on your internet connection, the docker application should pull a new image from the Docker Hub, the default repository.

Example output if successful:

Now that the Docker image has been downloaded as above, Docker created a new container from the image named hello-world.

How to search for Docker Images

To search for images that are located on Docker Hub by using the docker search command.

Example:

docker search ubuntu

Example output:

As above, a list of all images that names match the search command string you executed. After the description, you can find three columns.

  • STARS – Number of votes received in the community, higher is always good.
  • OFFICIAL – Images that are built and supported by the Docker company.
  • AUTOMATED – Images that are built from community, not officially endorsed by the Docker company. Use at own risk.

How to pull Docker Image

After searching for an image, you can pull these with the docker pull command.

docker pull ubuntu

Example output:

Next, verify the image exists on your system:

docker images

Example output:

As above, you got the ubuntu image and the original hello-world image you created earlier in the tutorial for testing purposes. The output also gives information on the tag, image id, creation, and size.

How to run a Docker Container from Image

Now that you have learned the basics, you can now run the ubuntu image that you downloaded. To do this, use the following command with the -it flag that will allow you access with the container using shell access:

docker run -it ubuntu

Note, as with the hello-word example, if an image has not been downloaded, the docker run command is executed, the Docker client will first download the image then run the container using it.

You will now be in the shell container, as you can see with the following output:

root@75b1115bacfd:/# 

The output will display your container ID, which in the case of the tutorial is 75b1115bacfd. Please note this ID, as you will need it for management purposes, such as removing the container at a later stage.

How to install a package in Docker Container

To install packages inside your Docker container is quite easy; it is basically the same as operating in your main Ubuntu system.

For example, you can test by installing some packages.

Install Nginx webapplication:

apt install nginx

Example output:

Type Y, then press the ENTER BUTTON to proceed with the installation.

You will more than likely receive a prompt to select your geographic area on first-time installing a package.

Example:

Select the geographic location closest to you by typing in the number and then pressing the ENTER KEY.

Next, you will be prompted to select the closet city; as with the geographic location, select the closet location and hit the ENTER KEY.

Example:

Verify the Nginx installation on your Docker container using the following version command:

nginx -v
nginx version: nginx/1.18.0 (Ubuntu)

How to update packages in Docker Container

To update packages inside the Docker container, you can use the apt update command without sudo or root because you already operate as the container’s root user.

Example:

apt update

Then upgrade as you would as if you were operating in your Ubuntu operating system:

apt upgrade 

How to remove packages in Docker Container

The process to remove packages in your Docker container is the same as installing them on your container. To remove the package you installed previously, for our example it was Nginx, use the following command:

apt autoremove nginx

Example output:

Type Y, then press the ENTER BUTTON to proceed with the uninstallation.

How to exit Docker Container

To exit your Docker container, use the following command:

exit

How to list Docker Containers

Now that you have exited as above back into your main operating system. You can utilize the docker ps command that will list the activated Docker command in your system:

sudo docker ps

Example output:

An alternative command is to use the docker ps with the -a flag, and this will list all Docker containers that are both active and inactive.

sudo docker ps -a

Example output:

As you can see above, there is one active container and two nonactives.

Another handy command is the docker ps with the -l flag, listing the last created container.

sudo docker ps -l

Example output:

Note the names of the containers; you can use these instead of the container IDS; for example, above, container ID 5c9785bbfd75 is named musing_lehmann.

How to Start a Docker Container

To start a Docker container, you need to get the container ID which, if forgotten, can be quickly found using the docker ps command. Next, execute the following command as an example of starting a container:

sudo docker start 5c9785bbfd75

To verify the status to see if it is active, use the docker ps command:

sudo docker ps

Example output:

As you can see, the container ID 5c9785bbfd75 is now active.

How to Stop a Docker Container

To stop a Docker container is the same as starting the container but in reverse with the stop option used.

sudo docker stop 5c9785bbfd75

Now use the docker ps command again to see the status:

Example output:

As above, you can see the container ID 5c9785bbfd75 is now inactive.

How to Remove a Docker Container

Once you have finished or no longer require the container, you can remove it using the docker rm command with the container ID or the container name. For example, remove the test container hello-world.

sudo docker rm 7f00ad33be63

Alternatively, you can delete your container ID by the name that Docker assigned. In the tutorial, the container ID 7f00ad33be63 (hello-world container) is named nifty_gagarin. To remove it, use the following:

sudo docker rm nifty_gagarin

Example output:

Comments and Conclusion

In the tutorial, you learned how to install Docker on Ubuntu 20.04, work with images and containers. From here, you can continue to learn about how to push and commit changes to the Docker Hub if you need to share or back images up. To sign up for an account is free, and most plans are very affordable, with business being the highest at 21 dollars; if interested, visit the sign-up page and create an account.

Overall, Docker is very popular as it revolutionized the way development is done these days with its ease of use, security, and physical resource requirements are less of a virtual machine as seen the platform skyrocket in the software industry. The debate now rages on which is more secure between virtual machines and docker. However, both can be dangerous, and good practices can stop most security issues with whatever virtualization you choose.



Follow LinuxCapable.com!

Like to get automatic updates? Follow us on one of our social media accounts!