Container foundations

Run and inspect a container

Start a web server container, publish its port, inspect its state, read its logs, and remove it deliberately.

Before building your own image, run one somebody else made. If something goes wrong, you’ll know it’s a Docker problem and not a problem with your application.

We’ll use nginx:alpine, a small web server image.

Start the container

docker run --name course-web -d -p 8080:80 nginx:alpine

Three flags here, and you’ll use them constantly:

  • --name course-web gives the container a name you choose. Without it Docker invents one like quirky_hopper, and you have to look it up every time.
  • -d runs the container in the background (detached) and gives you the terminal back.
  • -p 8080:80 publishes a port. Nginx listens on port 80 inside the container. This maps port 8080 on your machine to it.

That last point is important. A process listening inside a container is not reachable from your machine unless you publish the port. Isolation cuts both ways.

Open http://localhost:8080 in the browser. You should see the “Welcome to nginx!” page.

Look at what’s running

docker ps lists running containers:

docker ps

You’ll see the container ID, the image (nginx:alpine), the status, the port mapping (0.0.0.0:8080->80/tcp), and the name.

To see what the main process printed, use docker logs:

docker logs course-web

Nginx writes its access log to standard output, so every request you made from the browser shows up here.

docker inspect gives you everything Docker knows about the container as JSON: the image, the command, the network settings, the mounts, the state:

docker inspect course-web

It’s long. I usually pipe it to less, or use --format to pull out one field, which we’ll do later in the course.

The lifecycle

docker run does several things in one go: it creates the container, then starts its main process. You can also do them separately with docker create and docker start.

Stopping a container doesn’t delete it. A stopped container keeps its writable layer, and you can inspect it or start it again. Only docker rm removes it. And removing a container doesn’t remove the image it came from, nor any volume you attached to it.

When you’re done, remove it:

docker rm -f course-web

-f stops it first if it’s still running.

When a container dies

If the main process exits, the container stops. Start from two things: the exit code and the logs. docker logs works on a stopped container too. Getting a shell inside with docker exec is useful, but only while the container runs. You can’t exec into a stopped container.

Try this: start the container, find the image name and the port mapping in docker ps, then remove it.

Lesson completed