# Other people's images: databases, tools and runtimes

Run Postgres and Redis without installing them, use CLI tools that vanish when done, run code with any language version, and pick images you can trust.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 5. About 30 minutes, beginner. Source: https://devops.rajeev.pro/courses/docker/05-third-party-images

## What you will learn

- Run Postgres and Redis in containers, configured with environment variables
- Wait for a database to be ready, and connect to it from inside and outside the container
- Run CLI tools from images with --rm, feeding them files and standard input
- Run code with an exact language version by mounting your folder into a runtime image
- Choose an image you can trust, and read its documentation for the settings it needs

## Somebody already packaged it

Before container images, developers installed every database client, language runtime and helper tool on each
workstation. Versions then differed between teammates, and a one-off dependency stayed installed long after
the task ended. A container image packages a tool and its runtime so you can run it without adding those
packages to the host.

Need Postgres for a project, a different Python version, or `jq` just once? Run an image that its publisher
maintains and documents. Docker downloads the image, starts its configured process, and removes the temporary
container when the command exits if you pass `--rm`. The image remains cached until you remove it, which makes
the next run faster.

This lesson uses images for local services and one-off tools, and shows how to check who publishes an image
before trusting it.

> **Figure.** A laptop with only Docker installed. Two long-running services started with -d: postgres:17-alpine on 127.0.0.1:5432 configured with POSTGRES_PASSWORD, and redis:8-alpine on 127.0.0.1:6379. Beside them, one-off tools run with --rm: jq, python:3.13-slim running total.py from the mounted current folder, curl, and the psql client. Below, how to pick an image: official or verified publisher, a pinned tag, slim or alpine variants, and the image's own documentation for its environment variables.
>
> Services run in the background; tools run once with --rm. Nothing gets installed on the machine itself.

## Databases in a minute

```sh
$ docker run -d --name db -e POSTGRES_PASSWORD=devpass -p 127.0.0.1:5432:5432 postgres:17-alpine
$ docker exec db pg_isready -h 127.0.0.1 -U postgres    # ready yet? (over TCP: see below)
127.0.0.1:5432 - accepting connections
$ docker exec db psql -h 127.0.0.1 -U postgres -c "create table orders(id serial primary key, item text);
    insert into orders(item) values ('book'),('pen'); select * from orders;"
CREATE TABLE
INSERT 0 2
 id | item
----+------
  1 | book
  2 | pen
(2 rows)
```

A database needs a moment to initialise, so scripts wait with `pg_isready` (or `docker compose` health
checks, lesson 9) instead of `sleep`. There's a trap here: on its **first** start, the official image runs a
temporary server, listening only on a local socket, to create the database, then restarts. A plain
`pg_isready` says "ready" during that temporary phase and the next command fails with `connection to server
on socket … failed`. Checking over TCP with `-h 127.0.0.1` waits for the real server, because the temporary
one never opens a TCP port. Forget the password and the container stops straight away, with the
reason in its logs:

```sh
$ docker run -d --name db2 postgres:17-alpine
$ docker ps -a --filter name=db2 --format '{{.Names}} {{.Status}}'
db2 Exited (1) 3 seconds ago
$ docker logs db2
Error: Database is uninitialized and superuser password is not specified.
       You must specify POSTGRES_PASSWORD to a non-empty value for the
       superuser. For example, "-e POSTGRES_PASSWORD=password" on "docker run".
```

Redis is even quicker:

```sh
$ docker run -d --name cache -p 127.0.0.1:6379:6379 redis:8-alpine
$ docker exec cache redis-cli ping
PONG
$ docker exec cache redis-cli set visits 41 && docker exec cache redis-cli incr visits
OK
42
```

`127.0.0.1:` in `-p` keeps them reachable only from your own machine. These databases keep their data in the
container's writable layer, so `docker rm` deletes it; lesson 6 fixes that with volumes.

## Tools that leave nothing behind

Installing a tool for one command creates more host state to patch and clean up. A container can provide the
tool only for the duration of the command. `--rm` removes its container on exit, and `-i` keeps standard input
open so the process can read a file piped or redirected into it.

The commands below run jq with redirected input and run curl as a temporary container:

```sh
$ docker run --rm -i ghcr.io/jqlang/jq:1.8.1 '.orders[].item' < orders.json
"book"
"pen"
$ docker run --rm curlimages/curl:8.16.0 -sI https://example.com | head -1
HTTP/2 200
$ docker run --rm --network host postgres:17-alpine \
    psql "postgresql://postgres:devpass@127.0.0.1:5432/postgres" -c "select count(*) from orders;"
```

The last one borrows the Postgres image only for its `psql` client, so you get the exact client version that
matches the server. The images stay cached; next time they start instantly.

Use this pattern for formatters, database clients and diagnostics that do not need a long-lived service.
Remember that removing the container does not remove the downloaded image, and mount only the files the tool
needs. A common mistake is expecting `--rm` to clean up a named volume or an image; those are separate
resources and need their own lifecycle.

## Any language version

Projects often need a runtime version that differs from the host's, and upgrading the host runtime can break
other projects. A runtime image gives one command a specific Python or Node version without changing what is
installed on the machine.

Mount the project folder into the container and set the working directory to that mount. The container then
reads the same source files, while the image supplies the interpreter:

```sh
$ docker run --rm -v "$PWD":/work -w /work python:3.13-slim python total.py
total: 13.7
$ docker run --rm python:3.13-slim python --version
Python 3.13.16
$ docker run --rm node:22-alpine node -e 'console.log(process.version)'
v22.23.3
```

`-v "$PWD":/work` makes the current folder appear at `/work` inside, and `-w /work` starts the command there.
Need to check something against Python 3.12 as well? Change the tag. No conflicts with what's on your machine.

Use this for quick compatibility checks or reproducible local tools. Pin an appropriate version tag and check
the image's supported platforms before using it in CI. A common mistake is forgetting the mount or working
directory: the runtime starts, but it cannot find the source file because the host folder is not available at
the path the command expects.

## Choosing an image you can trust

An image runs code with access to the resources you pass into its container. A malicious or abandoned image
can therefore read mounted files, use environment variables or consume network access. Treat image selection
like dependency selection: check its publisher, source, update history and instructions before running it.

| Look for                                                   | Why                                                              |
| ---------------------------------------------------------- | ---------------------------------------------------------------- |
| **Docker Official Image** or **Verified Publisher** badge  | maintained, rebuilt for security fixes, documented               |
| a **pinned tag**: `postgres:17-alpine`, not `postgres`     | `latest` changes under you; a rebuild could jump a major version |
| `-slim` or `-alpine` variants                              | smaller download and fewer packages with vulnerabilities         |
| the image page's **environment variables** and **volumes** | how to configure it and where it keeps data                      |
| a linked source repository                                 | you can see how it's built                                       |

Prefer an official or verified publisher when one exists, pin a version rather than relying on `latest`, and
read the image's documentation for required variables and data paths. Smaller variants can reduce downloads,
but they may omit libraries the application expects. Scan images where that fits your workflow and rebuild
when the publisher releases security updates. A common mistake is assuming a popular tag is safe or
reproducible without checking who published it and what digest was actually pulled.

`-alpine` uses musl instead of glibc. That's fine for most images, but some compiled language packages behave
differently, so `-slim` (Debian, smaller) is the safer choice for Python and Node apps.

> **Dev passwords stay on dev.** `POSTGRES_PASSWORD=devpass` is fine for a database bound to `127.0.0.1` on your laptop. Anywhere else, read the password from a file or a secret (`POSTGRES_PASSWORD_FILE` is supported by the official image; lesson 11 covers secrets) and never commit it.

## Mission: A disposable dev stack

Without installing anything but Docker, run Postgres and Redis for local development, bound to your machine only; create a table and some rows; count visits in Redis; query the database with a psql client from an image; and summarise a JSON file with jq and Python run from images.

- You need: Docker
- You'll have: A table with two rows, a Redis counter, and jq and Python output, then everything removed

```sh
$ docker run -d --name db -e POSTGRES_PASSWORD=devpass -p 127.0.0.1:5432:5432 postgres:17-alpine
$ until docker exec db pg_isready -h 127.0.0.1 -U postgres >/dev/null; do sleep 1; done
$ docker exec db psql -h 127.0.0.1 -U postgres -c "create table orders(id serial, item text); insert into orders(item) values ('book'),('pen');"
$ docker run -d --name cache -p 127.0.0.1:6379:6379 redis:8-alpine
$ docker exec cache redis-cli incr visits
1
$ printf '{"orders":[{"item":"book","price":12.5},{"item":"pen","price":1.2}]}\n' > orders.json
$ printf 'import json\nd=json.load(open("orders.json"))\nprint("total:", sum(o["price"] for o in d["orders"]))\n' > total.py
$ docker run --rm -i ghcr.io/jqlang/jq:1.8.1 '[.orders[].price] | add' < orders.json
13.7
$ docker run --rm -v "$PWD":/work -w /work python:3.13-slim python total.py
total: 13.7
$ docker rm -f db cache
```

`until … pg_isready -h 127.0.0.1` waits for the real server, not the temporary first-start one, without
guessing a `sleep`. When you're done, `docker rm -f`
removes both containers, and with them their data: next lesson, you'll keep it.

## Try it

- Start Postgres with `-e POSTGRES_PASSWORD=devpass` and run `select version();` through docker exec.
- Start Postgres without the password and read why it exits with docker logs.
- Run `docker exec cache redis-cli ping` against a Redis container.
- Pipe a JSON file into `docker run --rm -i ghcr.io/jqlang/jq:1.8.1 .`.
- Run a Python script from your current folder with `-v "$PWD":/work -w /work python:3.13-slim`.
- Open the Docker Hub page of an image you use and find its environment variables and tags.

## Quiz

1. You run docker run -d postgres:17-alpine and it exits immediately. Why?
   - Postgres is broken
   - **It needs POSTGRES_PASSWORD to initialise the database; docker logs shows the message** (answer)
   - Port 5432 is in use
   - Alpine can't run Postgres
   Why: Official images document their environment variables. "Database is uninitialized and superuser password is not specified" means pass -e POSTGRES_PASSWORD=….

2. Why add --rm when running a tool like jq or curl from an image?
   - It runs faster
   - **The container is deleted when the command ends, so one-off runs don't pile up** (answer)
   - It removes the image
   - It is required for -i
   Why: The image stays cached, so the next run starts instantly; only the finished container is removed.

3. How does a container read a script in your current folder?
   - Containers can read your folders automatically
   - **Mount it: -v "$PWD":/work -w /work, then run the script from /work** (answer)
   - Copy it with docker cp first, always
   - Put it in the image
   Why: -v makes the folder visible inside; -w sets the working directory. Lesson 6 explains mounts fully.

4. Why publish a development database as -p 127.0.0.1:5432:5432 instead of -p 5432:5432?
   - It is faster
   - **Only your own machine can connect; 5432:5432 listens on every network address, including Wi-Fi** (answer)
   - Postgres requires it
   - There is no difference
   Why: A dev database with a weak password reachable from the café Wi-Fi is a real risk.

5. Which image is the safest default choice?
   - The one with the most stars from an unknown account
   - **A Docker Official Image or verified publisher, with a pinned version tag** (answer)
   - latest of anything
   - The biggest image
   Why: Official images are maintained, scanned and documented. Pin the tag so a rebuild doesn't silently change versions.

## Resources

- [Postgres official image](https://hub.docker.com/_/postgres) (Docker Hub)
- [Redis official image](https://hub.docker.com/_/redis) (Docker Hub)
- [Docker Docs: Docker Official Images](https://docs.docker.com/docker-hub/repos/manage/trusted-content/official-images/) (Docker Docs)
- [jq official image](https://github.com/jqlang/jq/pkgs/container/jq) (jqlang)
