Skip to main content
CodingMarble

Programming fundamentals

Docker for Beginners: Images, Containers and Compose

Docker packages an application and everything it needs into an image, and a container is a running instance of that image, so the app behaves the same on any machine with Docker. This guide walks through a working Dockerfile for a Node app, the ideas of layers, ports and volumes, a Compose file with a database, and when Docker is more trouble than it is worth.

By CodingMarble · Published · 5 min read

A laptop turned on showing code
Photo: Andras Vas on Unsplash

Images and containers are not the same thing

An image is a read-only package: an operating system's file layout, your runtime such as Node, your code and its dependencies, plus the command to start it. A container is a live process started from that image, with its own isolated filesystem and network. The relationship is like a class and an object, or a recipe and a meal. You can start many containers from one image, and deleting a container does not delete the image.

The reason developers use this is repeatability. If it works in the image, it works wherever the image runs, which removes a whole family of problems caused by different runtime versions or missing system packages. A container is not a full virtual machine: it shares the host's kernel, which makes it light and quick to start.

A Dockerfile, line by line

A Dockerfile is a list of build instructions. Here is one for a small Node web app that has a package.json, a package-lock.json and a server.js listening on port 3000. Choose the Node tag your project supports and check the official image page for current tags.

Prompt· Dockerfile for a small Node app
FROM node:lts-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]
  • FROM picks the base image to build on. The alpine variants are small, but some native packages behave differently on them, so switch to a Debian-based tag if you hit build errors.
  • WORKDIR sets the directory inside the image for the following commands.
  • COPY with only the package files, then RUN npm ci installs dependencies exactly as the lock file says. The --omit=dev flag skips development packages.
  • COPY . . then adds the rest of your code.
  • ENV sets an environment variable. EXPOSE documents the port but does not publish it.
  • USER node runs the app as a non-root user, which limits damage if it is compromised.
  • CMD is the start command. The array form runs the process directly so it receives stop signals correctly.

Layers and why instruction order matters

Each instruction creates a layer, and Docker reuses a layer from its build cache if the instruction and the files it depends on have not changed. When one layer changes, every layer after it is rebuilt. This is why the Dockerfile copies the package files first and installs dependencies before copying the rest of the code. Your code changes constantly but dependencies rarely do, so the slow install layer is reused on most builds.

Put a .dockerignore file next to the Dockerfile listing node_modules, .git and local .env files. Without it, COPY . . would pull your local node_modules into the image, bloat it, and risk shipping secrets baked into a layer that anyone with the image can extract.

Shell· Build the image, then run a container with a published port
docker build -t my-app .
docker run --rm -p 3000:3000 -e PORT=3000 my-app

Ports, volumes and environment variables

A container's network is isolated, so a service listening on port 3000 inside is unreachable from your browser until you publish it. The flag -p 3000:3000 maps host port 3000 to container port 3000, in the order host then container. If something on your machine already uses the host port, change the left number, for example 8080:3000.

A container's writable filesystem disappears when the container is removed. Anything that must survive, such as database files or uploads, belongs in a volume, a storage area managed by Docker, or a bind mount that links a folder from your computer. Environment variables, passed with -e or an env file, are how you give the same image different settings for development and production without rebuilding. Keep real secrets out of the image and out of the Dockerfile.

Docker Compose: an app and a database together

Real apps need more than one process. Compose describes several containers in one YAML file and starts them with a single command. The example runs the Node app and a PostgreSQL database. Inside the Compose network each service is reachable by its service name, so the app connects to the host db, not localhost.

Prompt· compose.yaml with an app and a database (the password comes from a local .env file)
services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: postgres://appuser:${DB_PASSWORD}@db:5432/appdb
    depends_on:
      - db

  db:
    image: postgres:16
    environment:
      POSTGRES_USER: appuser
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: appdb
    volumes:
      - dbdata:/var/lib/postgresql/data

volumes:
  dbdata:

Create a .env file beside it containing DB_PASSWORD with a value of your choice, keep that file out of version control, then run docker compose up. depends_on controls start order but does not wait for the database to be ready to accept connections, so your app should retry its first connection. The named volume dbdata keeps your data when containers are recreated, but docker compose down -v removes it. Check the current Postgres image documentation for the tag you should use.

Common beginner errors

The app runs but the browser cannot reach it: the port was not published, or the app listens only on 127.0.0.1 inside the container. Make the server listen on 0.0.0.0. A port is already allocated: another process or container holds the host port, so change the host side of the mapping. The app cannot reach the database at localhost: inside a container localhost means the container itself, so use the service name. Changes to code do not appear: you rebuilt nothing, so rebuild the image or mount your source as a bind mount during development.

The .dockerignore file and image size

Docker sends the whole build folder, called the build context, to the builder before running the first instruction. Anything in that folder can end up inside the image through COPY, and a large context also makes every build slower. A .dockerignore file lists paths to leave out, using the same idea as .gitignore.

Prompt· .dockerignore for a Node project
node_modules
.git
.env
.env.*
Dockerfile
compose.yaml
npm-debug.log
dist

Smaller images pull faster, start faster and expose less software to attack. The main levers are a slim base image, installing only production dependencies, and not copying files you do not need. A multi-stage build goes further: one stage installs everything and builds the app, and a second, clean stage copies in only the finished output. Run docker images to see the size of each image, and docker history my-app to see which layer contributed the most.

Debugging a container that exits immediately

A container lives only as long as its main process. If your start command crashes, or finishes, the container stops and docker ps shows nothing. The command docker ps -a lists stopped containers too, with their exit status. Then read what the process printed with docker logs, giving the container name or ID from that list.

Shell· Find out why a container stopped
docker ps -a
docker logs my-container
docker logs --tail 50 -f my-container

# Run a shell in a running container to look around
docker exec -it my-container sh

# Start a throwaway shell from the image if it will not stay up
docker run --rm -it --entrypoint sh my-app

The usual causes are a missing environment variable, a wrong file path in CMD, a dependency that was installed on your machine but not in the image, or the app being unable to reach its database at startup. Alpine images include sh rather than bash, which is why the commands above use sh.

Practical tip: when something works on your machine but not in the container, open a shell inside the image with the last command above and run the start command by hand. The error appears directly in your terminal, and you can inspect files, paths and variables as the app sees them.

When Docker is not needed

Docker adds a layer to learn, debug and maintain. A static site, a simple site on a managed platform that builds your code for you, or a solo project with one runtime version often gains little from it. It earns its place when several people need identical environments, when the app needs services such as a database or queue locally, or when you deploy to a server or platform that runs containers. Choose it for a reason you can state, not because it feels professional.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.