Running containers and ports

Docker · lesson 4 of 31 · 3 min read

Start, inspect and stop containers, and map a container port onto your host without guesswork.

Open this lesson in the learning hub

Key points

  • -p 8080:9090 reads host:container. Get it backwards and you will stare at a dead port.
  • Plain -p 8080:8080 listens on every host interface. -p 127.0.0.1:8080:8080 keeps it on your machine only.
  • Your app must bind 0.0.0.0, not localhost. Inside a container, localhost is the container.
  • --rm deletes the container when it exits. Use it for anything throwaway.
  • docker logs -f and docker exec -it ... sh are the two debugging tools you will use daily.

Example

docker build -t myapp:1.0 .
docker run -d --name myapp -p 127.0.0.1:8080:8080 myapp:1.0

docker ps                    # is it up?
docker logs -f myapp         # what is it saying?
docker exec -it myapp sh     # poke around inside

docker stop myapp
docker rm myapp

# throwaway run that cleans up after itself
docker run --rm -p 8080:8080 myapp:1.0

Host port on the left, container port on the right, and bind 0.0.0.0 inside.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Docker course, and every lesson in it is listed on the Docker contents page.