Install Docker and run your first container
1. Install Docker
- Mac / Windows: install Docker Desktop from docker.com. It includes the engine, the CLI, Compose and a GUI.
- Linux: install Docker Engine with your package manager (Docker's docs have one-liners for Ubuntu, Debian, Fedora and more). Then add yourself to the
dockergroup so you don't needsudo:
bash
sudo usermod -aG docker $USER # then log out and back inCheck that it works:
bash
docker --version
docker info2. Hello, world
bash
docker run hello-worldHere's what just happened:
- Docker looked for the
hello-worldimage locally and didn't find it. - It pulled (downloaded) the image from Docker Hub.
- It created a container from the image and ran it.
- The container printed a message and exited.
3. Run a real web server
bash
docker run -d -p 8080:80 --name web nginxOpen http://localhost:8080 and you'll see the Nginx welcome page, served from a container.
| Flag | Meaning |
|---|---|
-d |
Detached: run in the background |
-p 8080:80 |
Map port 8080 on your machine to port 80 in the container |
--name web |
Give it a friendly name (otherwise Docker picks a random one) |
nginx |
The image to run |
4. Manage containers
bash
docker ps # running containers
docker ps -a # all containers, including stopped ones
docker logs web # see the output
docker logs -f web # follow logs live (Ctrl+C to stop following)
docker stop web # stop gracefully
docker start web # start again
docker rm -f web # remove (force-stops if running)5. Go inside a container
bash
docker run -it --rm ubuntu bash-itgives you an interactive terminal.--rmdeletes the container automatically when you exit.
You're now in a Ubuntu shell, even on a Mac or Windows machine. Try cat /etc/os-release, ls / or apt update. Type exit to leave. Nothing you did affects your computer.
You can also open a shell in an already-running container:
bash
docker run -d --name web nginx
docker exec -it web sh # run a shell inside it6. Run tools without installing them
Containers are a clean way to try languages and tools:
bash
docker run --rm python:3.12 python -c "print('Hello from Python in Docker')"
docker run --rm node:22 node -e "console.log(process.version)"
docker run --rm -it postgres:16 psql --versionClean up
bash
docker container prune # remove all stopped containers
docker image prune # remove dangling images
docker system df # how much disk Docker is usingPractice
- Run the
httpd(Apache) image on port 9090 in the background with the nameapache. - View its logs, then open a shell inside it and find the
index.htmlit serves (hint:/usr/local/apache2/htdocs). - Stop and remove it.
✎ Check your understanding
1.What does -p 3000:80 do?
2.What does --rm do?