Introduction
Docker is an exertion that simplifies the process of managing exertion processes successful containers. Containers fto you tally your applications successful resource-isolated processes. They’re akin to virtual machines, but containers are much portable, much resource-friendly, and much limited connected the big operating system.
For a elaborate preamble to the different components of a Docker container, cheque retired The Docker Ecosystem: An Introduction to Common Components.
In this tutorial, you’ll instal and usage Docker Community Edition (CE) connected Ubuntu 20.04. You’ll instal Docker itself, activity pinch containers and images, and push an image to a Docker Repository.
Note
This article will locomotion you done installing Docker connected an Ubuntu server. If you wanted a 1-click measurement to deploy a Docker exertion to a unrecorded server, return a look astatine DigitalOcean App Platform.
Prerequisites
To travel this tutorial, you will request the following:
- One Ubuntu 20.04 server group up by pursuing the Ubuntu 20.04 first server setup guide, including a sudo non-root personification and a firewall.
- An relationship connected Docker Hub if you wish to create your ain images and push them to Docker Hub, arsenic shown successful Steps 7 and 8.
Step 1 — Installing Docker
The Docker installation package disposable successful the charismatic Ubuntu repository whitethorn not beryllium the latest version. To guarantee we get the latest version, we’ll instal Docker from the charismatic Docker repository. To do that, we’ll adhd a caller package source, adhd the GPG cardinal from Docker to guarantee the downloads are valid, and past instal the package.
First, update your existing database of packages:
sudo apt updateNext, instal a fewer prerequisite packages which fto apt usage packages complete HTTPS:
sudo apt install apt-transport-https ca-certificates curl software-properties-commonThen adhd the GPG cardinal for the charismatic Docker repository to your system:
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -Add the Docker repository to APT sources:
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable"This will besides update our package database pinch the Docker packages from the recently added repo.
Make judge you are astir to instal from the Docker repo alternatively of the default Ubuntu repo:
apt-cache argumentation docker-ceYou’ll spot output for illustration this, though the type number for Docker whitethorn beryllium different:
Output of apt-cache argumentation docker-ce
docker-ce: Installed: (none) Candidate: 5:19.03.9~3-0~ubuntu-focal Version table: 5:19.03.9~3-0~ubuntu-focal 500 500 https://download.docker.com/linux/ubuntu focal/stable amd64 PackagesNotice that docker-ce is not installed, but the campaigner for installation is from the Docker repository for Ubuntu 20.04 (focal).
Finally, instal Docker:
sudo apt install docker-ceDocker should now beryllium installed, the daemon started, and the process enabled to commencement connected boot. Check that it’s running:
sudo systemctl position dockerThe output should beryllium akin to the following, showing that the work is progressive and running:
Output
● docker.service - Docker Application Container Engine Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled) Active: progressive (running) since Tue 2020-05-19 17:00:41 UTC; 17s ago TriggeredBy: ● docker.socket Docs: https://docs.docker.com Main PID: 24321 (dockerd) Tasks: 8 Memory: 46.4M CGroup: /system.slice/docker.service └─24321 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sockInstalling Docker now gives you not conscionable the Docker work (daemon) but besides the docker bid statement utility, aliases the Docker client. We’ll research really to usage the docker bid later successful this tutorial.
Step 2 — Executing the Docker Command Without Sudo (Optional)
By default, the docker bid tin only beryllium tally the root personification aliases by a personification successful the docker group, which is automatically created during Docker’s installation process. If you effort to tally the docker bid without prefixing it pinch sudo aliases without being successful the docker group, you’ll get an output for illustration this:
Output
docker: Cannot link to the Docker daemon. Is the docker daemon moving connected this host?. See 'docker tally --help'.If you want to debar typing sudo whenever you tally the docker command, adhd your username to the docker group:
sudo usermod -aG docker ${USER}To use the caller group membership, log retired of the server and backmost in, aliases type the following:
su - ${USER}You will beryllium prompted to participate your user’s password to continue.
Confirm that your personification is now added to the docker group by typing:
groupsOutput
sammy sudo dockerIf you request to adhd a personification to the docker group that you’re not logged successful as, state that username explicitly using:
sudo usermod -aG docker usernameThe remainder of this article assumes you are moving the docker bid arsenic a personification successful the docker group. If you take not to, please prepend the commands pinch sudo.
Let’s research the docker bid next.
Step 3 — Using the Docker Command
Using docker consists of passing it a concatenation of options and commands followed by arguments. The syntax takes this form:
docker [option] [command] [arguments]To position each disposable subcommands, type:
dockerAs of Docker 19, the complete database of disposable subcommands includes:
Output
connect Attach local modular input, output, and correction streams to a moving container build Build an image from a Dockerfile perpetrate Create a caller image from a container's changes cp Copy files/folders betwixt a instrumentality and the section filesystem create Create a caller container diff Inspect changes to files aliases directories connected a container's filesystem events Get existent time events from the server exec Run a command in a moving container export Export a container's filesystem arsenic 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 accusation connected Docker objects kill Kill 1 aliases more moving containers load Load an image from a tar archive aliases STDIN login Log in to a Docker registry logout Log retired from a Docker registry logs Fetch the logs of a container region Pause each processes wrong 1 aliases more containers larboard List larboard mappings aliases a circumstantial mapping for the container ps List containers propulsion Pull an image aliases a repository from a registry push Push an image aliases a repository to a registry rename Rename a container restart Restart 1 aliases more containers rm Remove 1 aliases more containers rmi Remove 1 aliases more images tally Run a command in a caller container prevention Save 1 aliases more images to a tar archive (streamed to STDOUT by default) hunt Search the Docker Hub for images commencement Start 1 aliases more stopped containers stats Display a unrecorded watercourse of container(s) assets usage statistics extremity Stop 1 aliases more moving containers tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE top Display the moving processes of a container unpause Unpause each processes wrong 1 aliases more containers update Update configuration of 1 aliases more containers type Show the Docker type information wait Block until 1 aliases more containers stop, then people their exit codesTo position the options disposable to a circumstantial command, type:
docker docker-subcommand --helpTo position system-wide accusation astir Docker, use:
docker infoLet’s research immoderate of these commands. We’ll commencement by moving pinch images.
Step 4 — Working pinch Docker Images
Docker containers are built from Docker images. By default, Docker pulls these images from Docker Hub, a Docker registry managed by Docker, the institution down the Docker project. Anyone tin big their Docker images connected Docker Hub, truthful astir applications and Linux distributions you’ll request will person images hosted there.
To cheque whether you tin entree and download images from Docker Hub, type:
docker tally hello-worldThe output will bespeak that Docker successful moving correctly:
Output
Unable to find image 'hello-world:latest' locally latest: Pulling from library/hello-world 0e03bdcc26d7: Pull complete Digest: sha256:6a65f928fb91fcfbc963f7aa6d57c8eeb426ad9a20c7ee045538ef34847f44f1 Status: Downloaded newer image for hello-world:latest Hello from Docker! This connection shows that your installation appears to beryllium moving correctly. ...Docker was initially incapable to find the hello-world image locally, truthful it downloaded the image from Docker Hub, which is the default repository. Once the image downloaded, Docker created a instrumentality from the image and the exertion wrong the instrumentality executed, displaying the message.
You tin hunt for images disposable connected Docker Hub by utilizing the docker bid pinch the hunt subcommand. For example, to hunt for the Ubuntu image, type:
docker hunt ubuntuThe book will crawl Docker Hub and return a listing of each images whose sanction lucifer the hunt string. In this case, the output will beryllium akin to this:
Output
NAME DESCRIPTION STARS OFFICIAL AUTOMATED ubuntu Ubuntu is simply a Debian-based Linux operating sys… 10908 [OK] dorowu/ubuntu-desktop-lxde-vnc Docker image to supply HTML5 VNC interface … 428 [OK] rastasheep/ubuntu-sshd Dockerized SSH service, built connected top of offi… 244 [OK] consol/ubuntu-xfce-vnc Ubuntu instrumentality pinch "headless" VNC session… 218 [OK] ubuntu-upstart Upstart is an event-based replacement for th… 108 [OK] ansible/ubuntu14.04-ansible Ubuntu 14.04 LTS with ...In the OFFICIAL column, OK indicates an image built and supported by the institution down the project. Once you’ve identified the image that you would for illustration to use, you tin download it to your machine utilizing the propulsion subcommand.
Execute the pursuing bid to download the charismatic ubuntu image to your computer:
docker propulsion ubuntuYou’ll spot the pursuing output:
Output
Using default tag: latest latest: Pulling from library/ubuntu d51af753c3d3: Pull complete fc878cd0a91c: Pull complete 6154df8ff988: Pull complete fee5db0ff82f: Pull complete Digest: sha256:747d2dbbaaee995098c9792d99bd333c6783ce56150d1b11e333bbceed5c54d7 Status: Downloaded newer image for ubuntu:latest docker.io/library/ubuntu:latestAfter an image has been downloaded, you tin past tally a instrumentality utilizing the downloaded image pinch the tally subcommand. As you saw pinch the hello-world example, if an image has not been downloaded erstwhile docker is executed pinch the tally subcommand, the Docker customer will first download the image, past tally a instrumentality utilizing it.
To spot the images that person been downloaded to your computer, type:
docker imagesThe output will look akin to the following:
Output
REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest 1d622ef86b13 3 weeks agone 73.9MB hello-world latest bf756fb1ae65 4 months agone 13.3kBAs you’ll spot later successful this tutorial, images that you usage to tally containers tin beryllium modified and utilized to make caller images, which whitethorn past beryllium uploaded (pushed is the method term) to Docker Hub aliases different Docker registries.
Let’s look astatine really to tally containers successful much detail.
Step 5 — Running a Docker Container
The hello-world instrumentality you ran successful the erstwhile measurement is an illustration of a instrumentality that runs and exits aft emitting a trial message. Containers tin beryllium overmuch much useful than that, and they tin beryllium interactive. After all, they are akin to virtual machines, only much resource-friendly.
As an example, let’s tally a instrumentality utilizing the latest image of Ubuntu. The operation of the -i and -t switches gives you interactive ammunition entree into the container:
docker tally -it ubuntuYour bid punctual should alteration to bespeak the truth that you’re now moving wrong the instrumentality and should return this form:
Output
root@d9b100f2f636:/Note the instrumentality id successful the bid prompt. In this example, it is d9b100f2f636. You’ll request that instrumentality ID later to place the instrumentality erstwhile you want to region it.
Now you tin tally immoderate bid wrong the container. For example, let’s update the package database wrong the container. You don’t request to prefix immoderate bid pinch sudo, because you’re operating wrong the instrumentality arsenic the root user:
- apt update
Then instal immoderate exertion successful it. Let’s instal Node.js:
- apt install nodejs
This installs Node.js successful the instrumentality from the charismatic Ubuntu repository. When the installation finishes, verify that Node.js is installed:
- node -v
You’ll spot the type number displayed successful your terminal:
Output
v10.19.0Any changes you make wrong the instrumentality only use to that container.
To exit the container, type exit astatine the prompt.
Let’s look astatine managing the containers connected our strategy next.
Step 6 — Managing Docker Containers
After utilizing Docker for a while, you’ll person galore progressive (running) and inactive containers connected your computer. To position the active ones, use:
docker psYou will spot output akin to the following:
Output
CONTAINER ID IMAGE COMMAND CREATEDIn this tutorial, you started 2 containers; 1 from the hello-world image and different from the ubuntu image. Both containers are nary longer running, but they still beryllium connected your system.
To position each containers — progressive and inactive, tally docker ps pinch the -a switch:
docker ps -aYou’ll spot output akin to this:
1c08a7a0d0e4 ubuntu "/bin/bash" 2 minutes agone Exited (0) 8 seconds agone quizzical_mcnulty a707221a5f6c hello-world "/hello" 6 minutes agone Exited (0) 6 minutes agone youthful_curieTo position the latest instrumentality you created, walk it the -l switch:
docker ps -l CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1c08a7a0d0e4 ubuntu "/bin/bash" 2 minutes agone Exited (0) 40 seconds agone quizzical_mcnultyTo commencement a stopped container, usage docker start, followed by the instrumentality ID aliases the container’s name. Let’s commencement the Ubuntu-based instrumentality pinch the ID of 1c08a7a0d0e4:
docker commencement 1c08a7a0d0e4The instrumentality will start, and you tin usage docker ps to spot its status:
Output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1c08a7a0d0e4 ubuntu "/bin/bash" 3 minutes agone Up 5 seconds quizzical_mcnultyTo extremity a moving container, usage docker stop, followed by the instrumentality ID aliases name. This time, we’ll usage the sanction that Docker assigned the container, which is quizzical_mcnulty:
docker extremity quizzical_mcnultyOnce you’ve decided you nary longer request a instrumentality anymore, region it pinch the docker rm command, again utilizing either the instrumentality ID aliases the name. Use the docker ps -a bid to find the instrumentality ID aliases sanction for the instrumentality associated pinch the hello-world image and region it.
docker rm youthful_curieYou tin commencement a caller instrumentality and springiness it a sanction utilizing the --name switch. You tin besides usage the --rm move to create a instrumentality that removes itself erstwhile it’s stopped. See the docker tally thief bid for much accusation connected these options and others.
Containers tin beryllium turned into images which you tin usage to build caller containers. Let’s look astatine really that works.
Step 7 — Committing Changes successful a Container to a Docker Image
When you commencement up a Docker image, you tin create, modify, and delete files conscionable for illustration you tin pinch a virtual machine. The changes that you make will only use to that container. You tin commencement and extremity it, but erstwhile you destruct it pinch the docker rm command, the changes will beryllium mislaid for good.
This conception shows you really to prevention the authorities of a instrumentality arsenic a caller Docker image.
After installing Node.js wrong the Ubuntu container, you now person a instrumentality moving disconnected an image, but the instrumentality is different from the image you utilized to create it. But you mightiness want to reuse this Node.js instrumentality arsenic the ground for caller images later.
Then perpetrate the changes to a caller Docker image lawsuit utilizing the pursuing command.
docker perpetrate -m "What you did to the image" -a "Author Name" container_id repository/new_image_nameThe -m move is for the perpetrate connection that helps you and others cognize what changes you made, while -a is utilized to specify the author. The container_id is the 1 you noted earlier successful the tutorial erstwhile you started the interactive Docker session. Unless you created further repositories connected Docker Hub, the repository is usually your Docker Hub username.
For example, for the personification sammy, pinch the instrumentality ID of d9b100f2f636, the bid would be:
docker perpetrate -m "added Node.js" -a "sammy" d9b100f2f636 sammy/ubuntu-nodejsWhen you commit an image, the caller image is saved locally connected your computer. Later successful this tutorial, you’ll study really to push an image to a Docker registry for illustration Docker Hub truthful others tin entree it.
Listing the Docker images again will show the caller image, arsenic good arsenic the aged 1 that it was derived from:
docker imagesYou’ll spot output for illustration this:
Output
REPOSITORY TAG IMAGE ID CREATED SIZE sammy/ubuntu-nodejs latest 7c1f35226ca6 7 seconds agone 179MB ...In this example, ubuntu-nodejs is the caller image, which was derived from the existing ubuntu image from Docker Hub. The size quality reflects the changes that were made. And successful this example, the alteration was that NodeJS was installed. So adjacent clip you request to tally a instrumentality utilizing Ubuntu pinch NodeJS pre-installed, you tin conscionable usage the caller image.
You tin besides build Images from a Dockerfile, which lets you automate the installation of package successful a caller image. However, that’s extracurricular the scope of this tutorial.
Now let’s stock the caller image pinch others truthful they tin create containers from it.
Step 8 — Pushing Docker Images to a Docker Repository
The adjacent logical measurement aft creating a caller image from an existing image is to stock it pinch a prime fewer of your friends, the full world connected Docker Hub, aliases different Docker registry that you person entree to. To push an image to Docker Hub aliases immoderate different Docker registry, you must person an relationship there.
This conception shows you really to push a Docker image to Docker Hub. To study really to create your ain backstage Docker registry, cheque retired How To Set Up a Private Docker Registry connected Ubuntu 18.04.
To push your image, first log into Docker Hub.
docker login -u docker-registry-usernameYou’ll beryllium prompted to authenticate utilizing your Docker Hub password. If you specified the correct password, authentication should succeed.
Note: If your Docker registry username is different from the section username you utilized to create the image, you will person to tag your image pinch your registry username. For the illustration fixed successful the past step, you would type:
docker tag sammy/ubuntu-nodejs docker-registry-username/ubuntu-nodejsThen you whitethorn push your ain image using:
docker push docker-registry-username/docker-image-nameTo push the ubuntu-nodejs image to the sammy repository, the bid would be:
docker push sammy/ubuntu-nodejsThe process whitethorn return immoderate clip to complete arsenic it uploads the images, but erstwhile completed, the output will look for illustration this:
Output
The push refers to a repository [docker.io/sammy/ubuntu-nodejs] e3fbbfb44187: Pushed 5f70bf18a086: Pushed a3b5c80a4eba: Pushed 7f18b442972b: Pushed 3ce512daaf78: Pushed 7aae4540b42d: Pushed ...After pushing an image to a registry, it should beryllium listed connected your account’s dashboard, for illustration that show successful the image below.
If a push effort results successful an correction of this sort, past you apt did not log in:
Output
The push refers to a repository [docker.io/sammy/ubuntu-nodejs] e3fbbfb44187: Preparing 5f70bf18a086: Preparing a3b5c80a4eba: Preparing 7f18b442972b: Preparing 3ce512daaf78: Preparing 7aae4540b42d: Waiting unauthorized: authentication requiredLog successful pinch docker login and repetition the push attempt. Then verify that it exists connected your Docker Hub repository page.
You tin now usage docker propulsion sammy/ubuntu-nodejs to propulsion the image to a caller instrumentality and usage it to tally a caller container.
Conclusion
In this tutorial you installed Docker, worked pinch images and containers, and pushed a modified image to Docker Hub. Now that you cognize the basics, research the other Docker tutorials successful the DigitalOcean Community.