Docker Basics: Containers Made Simple
Running Containers
In this lesson you will
- Run a container with docker run
- Publish a port so you can reach it
- List, stop and remove containers
Introduction
The quickest way to learn Docker is to run something. You need Docker installed and running.
Your first container
Terminal
$ docker run hello-worldDocker looks for the hello-world image on your computer, downloads it from Docker Hub if needed, starts a container, prints a short welcome message, and exits.
Run a web server
Terminal
$ docker run -d -p 8080:80 --name my-web nginxWhat each part means:
-druns it in the background (detached).-p 8080:80publishes a port: traffic to port 8080 on your computer goes to port 80 inside the container.--name my-webgives the container a friendly name.nginxis the image: a popular web server.
Now open http://localhost:8080 in your browser. You should see the nginx welcome page.
Quick quiz
What does -p 8080:80 do?
Manage containers
Terminal
$ docker ps # list running containers
$ docker ps -a # list all containers, including stopped ones
$ docker logs my-web # see what the container printed
$ docker stop my-web # stop it
$ docker rm my-web # remove the stopped container
$ docker images # list images on your computerStopping a container does not delete it. Remove it with docker rm when you are done. Adding --rm to docker run removes the container automatically when it stops.
Run something interactively
Terminal
$ docker run -it ubuntu bash-it gives you an interactive terminal inside a fresh Ubuntu container. Type exit to leave. Anything you install in there disappears with the container, which is great for safe experiments.
Clean up
Images and stopped containers use disk space. Remove what you do not need, for example with docker rm and docker rmi image-name.
Try it yourself
Run nginx on port 8080, open it in your browser, read its logs, then stop and remove the container.
Summary
docker runstarts a container from an image, downloading it if needed.-druns in the background,-ppublishes a port and--namenames it.- Use
ps,logs,stopandrmto manage containers.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading