This guide will show you how to set up Docker in Ubuntu. Not only that! You will also see some useful examples and commands.
What is Docker?
Docker uses virtualization technology which in turn makes developing and deploying containerized applications a breeze! Virtualization allows the container to be deployed on any machine without any compatibility issues. So it makes your software simple to develop, deploy, use and maintain.
Docker Containers are, however, different from a typical virtual machine in that they act as micro-services, each with specific jobs. Each Docker container runs the operating system on isolated CPU processes, memory, and network resources. Because of this, you can be easily added, remove, start and stop it again without affecting the host operating system. Containers usually run one specific task such as MySQL database or Node.js application and network it together to scale them.
Unlike virtual machines, resources are shared directly with hosts. This allows you to run many docker containers. In addition, Docker uses less disk space as it can reuse files using the layered file system.
Heads up! You will require the following items for you to proceed:
- A server running Ubuntu 18.04 or 20.04
- A root password is configured on your server
Install the required dependencies
First, you will need to install some dependencies need by Docker in your server. You can install all these dependencies by running the following command:
apt-get install apt-transport-https ca-certificates curl gnupg2 software-properties-common -y
After installing all the required packages, you can proceed to install Docker.
By default, the latest version of Docker is not available in the Ubuntu default repository. So it is a good idea to install Docker from the official docker repository. But, first, let's see how to set up Docker on Ubuntu.
First, download and add the Docker GPG key with the following command:
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
Next, add the Docker repository using the APT command mentioned below. Finally, you can set your architecture to x86_64, amd64, armhf, or arm64.
add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
Once the repository is added, update the repository and install the latest version of the Docker with the following command:
apt-get update -y apt-get install docker-ce docker-ce-cli containerd.io -y
Now, you can verify the status of the Docker with the following command:
systemctl status docker
You should see the following output once Docker has been setup:
● docker.service - Docker Application Container Engine Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2020-06-16 09:25:58 AEST; 2 months 22 days ago Docs: https://docs.docker.com Main PID: 3353 (dockerd) Tasks: 36 Memory: 74.4M CGroup: /system.slice/docker.service ├─3353 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
How to use Docker?
Now that you have set up Docker on Ubuntu let's see how you use it.
The basic syntax of the Docker command is shown below:
docker [option] [command] [arguments]
You can list all available options with docker by running the following command:
You should see the complete list of docker subcommands in the following output:
Usage: docker [OPTIONS] COMMAND A self-sufficient runtime for containers Options: --config string Location of client config files (default "/home/anthony/.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/anthony/.docker/ca.pem") --tlscert string Path to TLS certificate file (default "/home/anthony/.docker/cert.pem") --tlskey string Path to TLS key file (default "/home/anthony/.docker/key.pem") --tlsverify Use TLS and verify the remote -v, --version Print version information and quit Management Commands: builder Manage builds config Manage Docker configs container Manage containers context Manage contexts engine Manage the docker engine image Manage images network Manage networks node Manage Swarm nodes plugin Manage plugins 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 deploy Deploy a new stack or update an existing stack 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 Run 'docker COMMAND --help' for more information on a command.
Run 'docker COMMAND --help' for more information on a command.
You can also display more information about Docker using the following command:
You should see the following output:
Client: Debug Mode: false Server: Containers: 2 Running: 1 Paused: 0 Stopped: 1 Images: 9 Server Version: 19.03.8 Storage Driver: zfs Zpool: rpool Zpool Health: ONLINE Parent Dataset: rpool/ROOT/ubuntu_yybki6/var/lib Space Used By Parent: 3448905728 Space Available: 946661916672 Parent Quota: no Compression: lz4 Logging Driver: json-file Cgroup Driver: cgroupfs 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: runc Default Runtime: runc Init Binary: docker-init containerd version: 7ad184331fa3e55e52b890ea95e65ba581ae3429 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd init version: fec3683 Security Options: apparmor seccomp Profile: default Kernel Version: 5.3.0-59-generic Operating System: Ubuntu 19.10 OSType: linux Architecture: x86_64 CPUs: 8 Total Memory: 7.356GiB Name: merlin ID: 5YZ2:UZF4:XECY:2HGI:ON4G:BSDU:3TQM:QOFX:MFO6:62L6:24WS:GOYN 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
Why not run a container now that you have set up Docker? Next, we will pull and run an Nginx container.
Pull a Docker Image from the Docker Hub
Now that you have set up Docker on Ubuntu let's see how you pull an image. A Docker image is a file built from an application's instructions or executable version used to execute code in a Docker container. All docker images are stored in the Docker Hub registry. You can pull your desired image from the Docker Hub using the "docker pull" command.
For example, pull the Nginx image from the Docker Hub, run the following command:
docker pull nginx
This will download an Nginx image from the Docker Hub to your local system. Once the download is completed, you should see the following output:
Using default tag: latest latest: Pulling from library/nginx bf5952930446: Pull complete cb9a6de05e5a: Pull complete 9513ea0afb93: Pull complete b49ea07d2e93: Pull complete a5e4a503d449: Pull complete Digest: sha256:b0ad43f7ee5edbc0effbc14645ae7055e21bc1973aee5150745632a24a752661 Status: Downloaded newer image for nginx:latest docker.io/library/nginx:latest
You can list your downloaded image by running the following command:
You should see all the downloaded images in the following output:
REPOSITORY TAG IMAGE ID CREATED SIZE nginx latest 4bb46517cac3 3 weeks ago 133MB
Run a Docker container
At this point, you have set up Docker on Ubuntu and downloaded the Nginx image from the Docker Hub. Now, you will need to run a container from the downloaded image.
There are two ways to run a container.
Run a Docker container in interactive mode
Running a docker container in interactive mode gives you interactive shell access into the container. You can do it using the switch -it as shown below:
docker run -it nginx /bin/bash
This command will bring inside the docker container as shown below:
Here, you can run any command in the container. For example, run the following command to update the package repository:
root@2cc89e08ffb2:/# apt-get update -y
You can exit from the container with the following command:
Run a Docker container in detached mode
You can run the docker container in detached mode or background using the -d switch. In this mode, you can run any other commands while the container is running.
You can run an Nginx container in detached mode using the following command:
docker run -it -d -p 8080:80 nginx
Once the container is started, you should see the following output:
You can now list the running containers with the following command:
Finally, you should see your Nginx container in the following output:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1db0b827baa2 nginx "/docker-entrypoint.…" 17 seconds ago Up 15 seconds 0.0.0.0:8080->80/tcp lucid_hofstadter
If you want to connect to your Nginx container, run the following command:
docker exec 1db0b827baa2
Where 1db0b827baa2 is the id of the Nginx container.
Run a Docker Container with Volume
Volume is used when you want to store the data on the host system and share them across all containers.
First, create a new volume directory on the host system:
Next, run the Nginx container and mount the /volume directory to the Nginx container on the /var/www/html directory.
docker run -it -d -v /volume:/var/www/html -p 8080:80 nginx
Next, connect to the Nginx container with the following command:
docker exec -it aba00ef3968b /bin/bash
Then, create a file named test.html inside /var/www/html directory:
Now, exit from the Nginx container with the following command:
Now, run the following command to list the available files in the /volume directory:
You should see the file named test.html, which you have created inside the Nginx container:
Copy File To and From the Docker Container
The simple and easiest way to copy a file to and from the running container is to use the "docker cp" command.
To copy a file named /etc/hosts from the host system to the Nginx container, run the following command:
docker cp /etc/hosts aba00ef3968b:/opt/
To copy a file named /etc/fstab from the Nginx container to the host system, run the following command:
docker cp aba00ef3968b:/etc/fstab /opt/
Start, Stop and Pause the Container
To stop the Nginx container, run the following command:
docker container stop aba00ef3968b
To start the Nginx container, run the following command:
docker container start aba00ef3968b
You can also pause the Nginx container using the following command:
docker container pause aba00ef3968b
To stop all running containers, run the following command:
docker container stop $(docker container ls -aq)
Remove Docker Container
To remove a container, you will need to stop it first.
For example, stop the Nginx container with the following command:
docker container stop aba00ef3968b
Next, remove the Nginx container using the following command:
docker container rm aba00ef3968b
If you want to remove all stopped containers, run the following command:
docker container rm $(docker container ls -aq)
Remove Docker Images
To remove the Docker images, list all images in your system with the following command:
You should see the following output:
REPOSITORY TAG IMAGE ID CREATED SIZE nginx latest 4bb46517cac3 3 weeks ago 133MB
Now, remove the Nginx image with the following command:
docker image rm 4bb46517cac3
You should see the following output if any container uses the image:
Error response from daemon: conflict: unable to delete 4bb46517cac3 (cannot be forced) - image is being used by running container 798c8c54736c
In this case, you will need to stop that container then remove the image.
To remove all unused images in your system, run the following command:
docker image prune -a
You will be asked to confirm before removing the image as shown below:
WARNING! This will remove all images without at least one container associated to them. Are you sure you want to continue? [y/N] y Deleted Images: untagged: nginx:latest untagged: nginx@sha256:b0ad43f7ee5edbc0effbc14645ae7055e21bc1973aee5150745632a24a752661 deleted: sha256:4bb46517cac397bdb0bab6eba09b0e1f8e90ddd17cf99662997c3253531136f8 deleted: sha256:80b21afd8140706d5fe3b7106ae6147e192e6490b402bf2dd2df5df6dac13db8 deleted: sha256:0f04ae71e99f5ef9021b92f76bac3979e25c98d73a51d33ce76a78da6afa9f27 deleted: sha256:9a14852344d88a1fdf8297914729834521ec1c77a27e7e7e394f9c1ef9b87f9d deleted: sha256:74299126f8099031c5bbd4774147f4ab6b0d0c3afcec774be65d4d07b956752e deleted: sha256:d0f104dc0a1f9c744b65b23b3fd4d4d3236b4656e67f776fe13f8ad8423b955c Total reclaimed space: 132.6MB
Wrapping up how to set up Docker on Ubuntu
In the above guide, you learned what Docker is, set up Docker, and several commands to manage the Docker container. Therefore, you should ow have basic knowledge of Docker. You can now explore docker and deploy your application in a containerized environment.
You may also be interested in
About the Authors
Anto's editorial team loves the cloud as much as you! Each member of Anto's editorial team is a Cloud expert in their own right. Anto Online takes great pride in helping fellow Cloud enthusiasts. Let us know if you have an excellent idea for the next topic! Contact Anto Online if you want to contribute.
Support the Cause
Support Anto Online and buy us a coffee. Anything is possible with coffee and code.