Skip to the page

Docker for developers · mid

Why it works on your laptop and breaks in the container

Containers change the network, the user and the file system. Most laptop-to-container bugs come from localhost, binding to 127.0.0.1, running as non-root, writing to the image, and the CPU architecture.

The notes

What you must know

  • localhost inside a container is the container itself. Use the compose service name, or host.docker.internal on Docker Desktop for something running on the laptop.
  • A server bound to 127.0.0.1 inside the container cannot be reached through a published port. Bind to 0.0.0.0.
  • invalid ELF header or exec format error: a binary or node_modules built on macOS or arm64 was copied into a Linux or amd64 image. Install inside the image, keep node_modules out with .dockerignore, and build with --platform linux/amd64 when nodes are amd64.
  • macOS file systems ignore case by default and Linux does not. require('./Config') for config.js works on a Mac and fails in the container.
  • Non-root: containers share the host kernel, so root inside plus a bug can mean root on the node. Ports below 1024 need a capability, so listen on 8080 and let the Service or load balancer map port 80.
  • Files copied in are owned by root, so a non-root app cannot write there. Do not write inside the image: uploads go to S3 and temporary files to a mounted emptyDir. If you must, create and chown one directory in the Dockerfile.
  • Read-only root file system: anything that writes to /tmp, caches or pycache fails. Mount a writable volume for those paths.
  • Compose for local development: services api, db and cache on one network, a named volume for data, a health check with pg_isready, and depends_on with condition: service_healthy. Plain depends_on only waits for the container to start, so the app still retries its connection.

The red pen

Common traps: mistake → fix

  • Mistake: depends_on waits until the database is ready

    Fix: It waits for the container to start. Use a health check condition, and retry in the app.

  • Mistake: Running as root in a container is harmless

    Fix: It is cheap to avoid and reduces risk from kernel and runtime bugs.

  • Mistake: localhost:5432 works in compose like on my laptop

    Fix: Use the service name, for example db:5432.

Easy to hard

Questions interviewers ask, easy to hard

  1. Why can the app not reach the database at localhost inside compose?
  2. My server listens on 127.0.0.1 and the published port does nothing. Why?
  3. What does exec format error mean?
  4. The app breaks after you add USER node. What are the likely causes?
  5. Write a compose file for an API, Postgres and Redis for local development.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview