# Docker basics: images, containers, ports, logs and exec

Run your first real containers: pull an image, start a web server, publish its port, read its logs, open a shell inside, and stop, start and remove it, knowing what each step changes.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 4. About 30 minutes, beginner. Source: https://devops.rajeev.pro/courses/docker/04-docker-basics

## What you will learn

- Tell an image from a container, and list both
- Run containers in the background, in the foreground and interactively, with names and --rm
- Publish a container port to the host with -p, and read docker ps's PORTS column
- Read a container's output with docker logs, and run commands inside it with docker exec
- Stop, start and remove containers, knowing what each one keeps and deletes

## Images and containers

Before Docker, a team might install the same app separately on every server. Versions drifted, and replacing
one server meant repeating the setup. Docker separates the packaged application from each running copy, so a
team can build or pull one artifact and start it consistently in several environments.

An **image** is a read-only template containing a filesystem and default startup settings. A **container** is
one created instance of that image, with its own process, network and writable layer (lesson 2). Docker reads
the image, adds the container's writable layer, and starts its configured command. You can run several
containers from the same image without changing the image itself.

This lesson pulls and runs nginx, publishes a port, inspects logs and process state, then compares stopping a
container with deleting it. The same image can be used again after a container is removed.

```sh
$ docker pull nginx:1.30-alpine
$ docker images
REPOSITORY   TAG           IMAGE ID       SIZE
nginx        1.30-alpine   970364228b1e   102MB
```

The **tag** (`1.30-alpine`) picks a version and variant. nginx releases stable versions with an even
minor number (1.30) and mainline with odd (1.31); `-alpine` is the small Alpine Linux base. Pin a tag in
anything you'll run twice: `nginx` alone means `nginx:latest`, which changes under you.

## docker run

```sh
$ docker run -d --name web -p 8080:80 nginx:1.30-alpine
3893cb7f5c00f1dfad90d75368565eaee2507636450773077c73bb9f8e20cfb9
$ docker ps
CONTAINER ID   IMAGE               STATUS          PORTS                                     NAMES
3893cb7f5c00   nginx:1.30-alpine   Up 13 seconds   0.0.0.0:8080->80/tcp, [::]:8080->80/tcp   web
```

| Flag           | Does                                                                     |
| -------------- | ------------------------------------------------------------------------ |
| `-d`           | run in the background and print the container ID                         |
| `--name web`   | a name to use instead of the ID                                          |
| `-p 8080:80`   | publish container port 80 on host port 8080                              |
| `-it`          | interactive with a terminal, for shells: `docker run -it alpine:3.22 sh` |
| `--rm`         | delete the container when it exits: for one-off commands                 |
| `-e KEY=value` | set an environment variable inside                                       |

Open http://localhost:8080 and nginx answers from inside the container:

> **Figure.** A real browser at localhost:8080 showing the default nginx page: Welcome to nginx! If you see this page, nginx is successfully installed and working.
>
> The page served by the container, through host port 8080.

## Publishing ports

Each container has its own network namespace, so port 80 inside isn't port 80 on your machine. `-p` connects
them: **host port first, container port second**.

```sh
$ curl -sI localhost:8080 | head -2
HTTP/1.1 200 OK
Server: nginx/1.30.6
$ docker run -d --name web2 -p 8081:80 nginx:1.30-alpine   # a second nginx: also port 80 inside
```

Both containers listen on port 80 in their own namespace; on the host they're 8080 and 8081. Two containers
can't publish the **same** host port: the second fails with `failed to bind host port 0.0.0.0:8080/tcp: address already in use`.

`0.0.0.0:8080` in `docker ps` means "every address of the host", so other machines can reach it. Bind to the
loopback only when that's what you want: `-p 127.0.0.1:8080:80`. Lesson 10 explains container networking
fully.

## Logs and exec

When a container runs in the background, its output is no longer printed in your terminal. `docker logs` reads
the main process's standard output and error streams, so applications should write operational logs there.
`docker exec` starts an additional process in an already-running container; it does not replace the main
process or create a new container.

```sh
$ docker logs web | tail -2
172.17.0.1 - - [16/Oct/2026:05:17:05 +0000] "HEAD / HTTP/1.1" 200 0 "-" "curl/8.18.0" "-"
172.17.0.1 - - [16/Oct/2026:05:17:05 +0000] "GET / HTTP/1.1" 200 896 "-" "curl/8.18.0" "-"
$ docker logs -f --since 5m web       # follow new lines, from the last 5 minutes
$ docker exec web nginx -v            # run a command inside
nginx version: nginx/1.30.6
$ docker exec -it web sh              # a shell inside; exit to leave (the container keeps running)
/ # ls /usr/share/nginx/html
50x.html    index.html
```

`docker logs` shows what the main process writes to **stdout and stderr**. The requests come from
`172.17.0.1`: the default bridge network's gateway, which is how your `curl` reached the container.

> **Video.** [Debugging Docker Containers with docker exec and docker logs || Docker Tutorial 5](https://www.youtube.com/watch?v=tLK9nNFHWH8) (TechWorld with Nana)

Use logs to inspect what the application reported, and use exec for a temporary diagnostic command. Prefer a
one-off command over leaving an interactive shell open. If logs are empty, check that the application writes
to stdout or stderr; `docker logs` does not automatically read arbitrary files inside the container. A common
mistake is treating `exec` as a durable fix: changes made inside a disposable container can disappear when it
is replaced.

## Stop, start, remove

> **Figure.** Animated. docker run creates a container from the nginx:1.30-alpine image and starts it: Up, with port 8080 published, so curl localhost:8080 gets 200 OK. docker stop ends the process: Exited (0); requests are refused but the container and its files, such as the access log, are kept. docker start runs the same container again with the same files. docker rm -f deletes the container and its writable layer, while the image stays for the next run.
>
> stop ends the process but keeps the container. rm deletes the container. Neither touches the image.

```sh
$ docker stop web                     # SIGTERM, then SIGKILL after 10 s
$ docker ps -a --filter name=web --format 'table {{.Names}}\t{{.Status}}'
NAMES     STATUS
web       Exited (0) 3 seconds ago
$ docker start web                    # the same container, the same files
$ docker rm -f web web2               # stop if needed, then delete
$ docker rmi nginx:1.30-alpine        # delete the image (only if no container uses it)
```

| Command        | The process                | The container and its files | The image |
| -------------- | -------------------------- | --------------------------- | --------- |
| `docker stop`  | ended                      | kept                        | kept      |
| `docker start` | started again              | same ones                   | kept      |
| `docker rm`    | (must be stopped, or `-f`) | **deleted**                 | kept      |
| `docker rmi`   |                            |                             | deleted   |

> **Name what you keep, --rm what you don't.** Give long-running containers a `--name`; add `--rm` to one-off commands (`docker run --rm alpine:3.22 date`) so stopped containers don't pile up in `docker ps -a`. Lesson 12 shows how to clean up the rest.

## Mission: Serve your own page from nginx

Run nginx in the background on host port 8080, replace its welcome page with your own using docker exec, prove it with curl, read the request in the logs, then stop, start and remove the container, checking what survives each step.

- You need: Docker
- You'll have: curl localhost:8080 showing your page, then a clean docker ps -a

```sh
$ docker run -d --name web -p 8080:80 nginx:1.30-alpine
$ docker exec web sh -c 'echo "<h1>Hello from my container</h1>" > /usr/share/nginx/html/index.html'
$ curl -s localhost:8080
<h1>Hello from my container</h1>
$ docker logs web | tail -1                      # your curl, logged
$ docker stop web && docker start web && curl -s localhost:8080
<h1>Hello from my container</h1>
$ docker rm -f web
$ docker run -d --name web -p 8080:80 nginx:1.30-alpine && sleep 1 && curl -s localhost:8080 | grep -o '<title>.*</title>'
<title>Welcome to nginx!</title>
$ docker rm -f web
```

Your page survives `stop` and `start` (same container, same writable layer), but not `rm`: the new container
starts from the untouched image, with nginx's default page. Lesson 6 shows how to keep data across containers.

## Try it

- Run `docker run -d --name web -p 8080:80 nginx:1.30-alpine` and open http://localhost:8080.
- Run `docker ps`, then `docker ps -a` after stopping the container, and compare the STATUS column.
- Follow the logs with `docker logs -f web` while you reload the page a few times.
- Open a shell inside with `docker exec -it web sh` and look at /usr/share/nginx/html.
- Run `docker run --rm -it alpine:3.22 sh`, exit, and check that `docker ps -a` doesn't list it.
- Start a second nginx on host port 8081, and explain why both can listen on container port 80.

## Quiz

1. What is the difference between an image and a container?
   - They are the same
   - **An image is a read-only template; a container is one running (or stopped) instance of it, with its own writable layer** (answer)
   - A container is a compressed image
   - Images run, containers are stored
   Why: One image can start any number of containers. docker images lists images; docker ps -a lists containers.

2. What does -p 8080:80 mean?
   - Container port 8080 to host port 80
   - **Host port 8080 forwards to port 80 inside the container** (answer)
   - Use 8080 MB of memory
   - Two containers
   Why: host:container. Each container has its own network namespace, so many containers can use port 80 inside, but each host port can be published only once.

3. After docker stop web, what still exists?
   - Nothing
   - **The container, with its files and logs; only its process ended. docker start runs it again** (answer)
   - Only the logs
   - Only the image
   Why: docker rm deletes the container and its writable layer. The image remains until docker rmi.

4. Where does docker logs get its output from?
   - A log file Docker searches for
   - **Everything the container's main process writes to stdout and stderr** (answer)
   - The host syslog
   - The image
   Why: That's why official images send their logs to stdout: nginx links its access log to /dev/stdout.

5. Which command opens a shell inside a running container?
   - docker run -it web sh
   - **docker exec -it web sh** (answer)
   - docker attach web sh
   - docker shell web
   Why: exec runs a new process inside an existing container. run would start a new container. Small images may have sh but not bash.

## Resources

- [Docker Docs: docker container run](https://docs.docker.com/reference/cli/docker/container/run/) (Docker Docs)
- [Docker Docs: publishing and exposing ports](https://docs.docker.com/get-started/docker-concepts/running-containers/publishing-ports/) (Docker Docs)
- [Docker Docs: docker container logs](https://docs.docker.com/reference/cli/docker/container/logs/) (Docker Docs)
- [nginx official image on Docker Hub](https://hub.docker.com/_/nginx) (Docker Hub)
