Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 111 ยท Dockerfiles

WORKDIR, USER, EXPOSE and LABEL

Learn the Dockerfile instructions that shape how a container runs: WORKDIR, running as a non-root USER, EXPOSE as documentation, OCI LABELs and STOPSIGNAL.

Once an image has its files and a start command, a handful of small instructions decide how comfortable and how safe it is to run. WORKDIR chooses the directory commands start in. USER decides who the process is: root or an ordinary account. EXPOSE documents which port the app listens on. LABEL attaches searchable metadata, and STOPSIGNAL picks the signal used to ask the app to stop.

None of them is dramatic on its own, but together they separate a throwaway experiment from an image you can hand to a colleague or run in production. Every output below was produced by building the Dockerfile shown. Examples use alpine:3.22 and nginx:1.27-alpine.

WORKDIR: where commands run

WORKDIR sets the working directory for the instructions that follow it (RUN, CMD, ENTRYPOINT, COPY, ADD) and for the container's main process when it starts. If the directory does not exist, Docker creates it, including any missing parents.

DOCKERFILE
FROM alpine:3.22
WORKDIR /app
RUN pwd
WORKDIR data
RUN pwd
WORKDIR /opt/new/deep
RUN pwd && ls -ld /opt/new/deep
ENV BASE=/srv
WORKDIR $BASE/site
COPY hello.txt .
CMD ["sh", "-c", "pwd && ls"]
CONSOLE
$ docker build --progress=plain --no-cache -t wd .
...
#7 0.556 /app
#9 0.324 /app/data
#11 0.431 /opt/new/deep
#11 0.432 drwxr-xr-x    2 root     root          4096 ...  /opt/new/deep
$ docker run --rm wd
/srv/site
hello.txt

Four things to notice:

  • WORKDIR data is relative, so it resolved against the previous WORKDIR and became /app/data. Relative paths stack, which is handy but easy to lose track of. Prefer absolute paths.
  • Missing directories were created automatically (/opt/new/deep), owned by root.
  • WORKDIR understands ENV variables ($BASE/site).
  • COPY hello.txt . put the file in /srv/site, because . means "the current WORKDIR".

Without any WORKDIR a container starts in /, the filesystem root:

CONSOLE
$ docker run --rm alpine:3.22 pwd
/

You can override the directory for a single run with -w:

CONSOLE
$ docker run --rm -w /tmp wd pwd
/tmp

Why not RUN cd /app?

A RUN cd only affects that one instruction, because each RUN starts a fresh shell (see FROM and RUN). It also never changes where the final container starts. WORKDIR fixes both problems and makes the Dockerfile easier to read, so use it instead of cd chains.

Set WORKDIR once near the top (/app is a common convention), then use relative paths like COPY . . and CMD ["./server"]. The image then has one obvious home for your application.

USER: stop running as root

By default, the process in a container runs as root (user ID 0). Root in a container is not the same as root on the host, but it is still powerful: it can write anywhere in the image's filesystem, bind to any port, and if some other weakness lets an attacker out of the container, root is a far better starting point than an ordinary account. Run your application as a non-root user whenever you can.

CONSOLE
$ docker run --rm alpine:3.22 id
uid=0(root) gid=0(root) groups=0(root),0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)

Creating and switching to a user

Create the account with a RUN (as root, since you have not switched yet), then switch with USER. On Alpine the tools are addgroup and adduser; on Debian and Ubuntu they are groupadd and useradd.

DOCKERFILE
FROM alpine:3.22
RUN addgroup -S -g 10001 app && adduser -S -u 10001 -G app -h /home/app app
WORKDIR /app
COPY --chown=app:app hello.txt .
USER app
CMD ["sh", "-c", "id && pwd && ls -l && touch /etc/test; echo exit=$?; touch note.txt && echo wrote note"]
CONSOLE
$ docker run --rm user-demo
uid=10001(app) gid=10001(app) groups=10001(app),10001(app)
/app
total 4
-rwxr-xr-x    1 app      app              6 ... hello.txt
touch: /etc/test: Permission denied
exit=1
touch: note.txt: Permission denied

Everything after USER (including RUN instructions and the final container) runs as that account. The container could no longer modify /etc. That is the point. But look at the last line: even touch note.txt inside /app failed. Why?

The classic ownership pitfall

WORKDIR /app ran while the build was still root, so Docker created /app owned by root. The file we copied with --chown belongs to app, but the directory does not, so the app cannot create new files in it.

CONSOLE
$ docker run --rm user-demo2
total 8
-rwxr-xr-x    1 root     root             6 ... hello.txt
drwxr-xr-x    2 root     root          4096 ... logs
touch: /app/x: Permission denied
exit=1
touch: /app/logs/x: Permission denied

(That second image skipped --chown, so even the copied file is root-owned.) There are three fixes; use whichever fits.

  1. Switch USER first, then WORKDIR. A directory created by WORKDIR after USER belongs to that user:
DOCKERFILE
FROM alpine:3.22
RUN addgroup -S app && adduser -S -G app app
USER app
WORKDIR /app
COPY --chown=app:app hello.txt .
CMD ["sh", "-c", "ls -ld /app; touch /app/note.txt && echo wrote note"]
CONSOLE
$ docker run --rm user-demo3
drwxr-xr-x    1 app      app           4096 ...  /app
wrote note
  1. Create and own the directory explicitly: RUN mkdir -p /app/data && chown -R app:app /app/data, only for the directories that need to be writable.
  2. Use COPY --chown=user:group for the files, as above. It sets ownership during the copy without adding a separate, space-wasting chown layer. See COPY and ADD.

Make only the directories the app must write to (uploads, cache, logs, a SQLite file) writable. Everything else should stay root-owned and read-only to the app: if the process is compromised, it cannot rewrite its own code.

Numeric IDs, nobody and what Docker checks

USER accepts a name or a number, optionally with a group (USER 1000:1000). A numeric ID needs no entry in /etc/passwd:

CONSOLE
$ docker run --rm num-demo
uid=1000 gid=1000 groups=1000

Many base images already include nobody (user 65534), which is a quick choice for a simple static service, though a dedicated account is clearer. A name that does not exist fails at start, not at build:

CONSOLE
$ docker run --rm ghost-demo
docker: Error response from daemon: unable to find user ghost: no matching entries in passwd file

Numeric IDs matter on Kubernetes (policies often require a numeric non-root ID) and when you use bind mounts, where file ownership on the host is compared by number, not name. Users and Permissions covers that in detail.

Overriding at run time

The Dockerfile sets the default; the caller can override it with --user / -u:

CONSOLE
$ docker run --rm --user root user-demo id
uid=0(root) gid=0(root) groups=0(root),0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)
$ docker run --rm -u 1234:1234 user-demo id
uid=1234 gid=1234 groups=1234
$ docker image inspect user-demo --format 'user={{.Config.User}}'
user=app

That --user root trick is how you debug permission problems or install a tool in a throwaway container.

Ports below 1024 used to require root. Docker now sets net.ipv4.ip_unprivileged_port_start to 0 inside containers (cat /proc/sys/net/ipv4/ip_unprivileged_port_start prints 0), so a non-root process can listen on port 80 without extra capabilities. Older runtimes and some orchestrators do not, so many images listen on 8080 anyway.

Switching back and forth

You can use USER several times. A typical pattern installs packages as root, then drops privileges for the rest of the image:

DOCKERFILE
FROM alpine:3.22
RUN apk add --no-cache curl            # runs as root
RUN addgroup -S app && adduser -S -G app app
USER app                               # everything below is non-root
WORKDIR /app
COPY --chown=app:app . .
CMD ["./run.sh"]

Put USER as late as you can while still before CMD. If you need root again for a step, write USER root and switch back after.

EXPOSE: documentation, not publishing

EXPOSE records that the container listens on a port. It does not open or publish anything. This misunderstanding trips up almost every beginner, so here it is with evidence. The image below declares port 80 and sets two other things we will use shortly:

DOCKERFILE
FROM nginx:1.27-alpine
LABEL org.opencontainers.image.title="Demo site" \
      org.opencontainers.image.version="1.0.0" \
      org.opencontainers.image.source="https://example.com/demo.git" \
      maintainer="[email protected]"
EXPOSE 80/tcp
STOPSIGNAL SIGQUIT

Start three containers: with no flag, with an explicit -p, and with -P:

CONSOLE
$ docker run -d --name web1 expose-demo
$ docker run -d --name web2 -p 127.0.0.1:18471:80 expose-demo
$ docker run -d --name web3 -P expose-demo
$ docker ps --format 'table {{.Names}}\t{{.Ports}}'
NAMES   PORTS
web3    0.0.0.0:32769->80/tcp
web2    127.0.0.1:18471->80/tcp
web1    80/tcp
$ curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18471/
200
  • web1 has EXPOSE 80 but nothing is reachable from the host. The 80/tcp in the PORTS column only says the image declared it.
  • web2 used -p host:container, which is what really publishes a port. The request on 18471 returned 200.
  • web3 used -P (capital), which publishes every exposed port to a random high port on the host. Port 32769 here (it varies). This is the one place where EXPOSE has a functional effect.

(Port numbers other than the one we chose will differ on your machine.) EXPOSE also helps tools: docker inspect shows ExposedPorts, and reverse proxies such as Traefik or nginx-proxy read it to find the right port automatically.

CONSOLE
$ docker image inspect expose-demo --format '{{json .Config.ExposedPorts}}'
{"80/tcp":{}}

Write the protocol when it is not TCP (EXPOSE 5353/udp) and list several ports on one line or in several instructions. Always add EXPOSE for your app's port: it is free documentation. Publishing Ports explains the -p forms and why binding to 127.0.0.1 matters.

Publishing with plain -p 8080:80 listens on all host interfaces (0.0.0.0), which may expose the service to your network. For local development bind explicitly: -p 127.0.0.1:8080:80.

LABEL attaches key/value pairs to an image. They do nothing at run time, but tools, registries and people read them. Labels inherited from the base image (nginx sets maintainer) are merged with yours, and the same key in your Dockerfile wins.

CONSOLE
$ docker image inspect expose-demo --format '{{range $k,$v := .Config.Labels}}{{$k}}={{$v}}{{"\n"}}{{end}}'
maintainer=team@example.com
org.opencontainers.image.source=https://example.com/demo.git
org.opencontainers.image.title=Demo site
org.opencontainers.image.version=1.0.0

The convention is reverse-DNS keys to avoid collisions. The Open Container Initiative defines standard ones under org.opencontainers.image.*; the most useful are title, description, version, source (the repository URL), revision (the git commit), created, licenses and authors. Registries like GitHub Container Registry use source to link an image to its repo.

You do not have to hard-code dynamic values. Pass them at build time:

CONSOLE
$ docker build --label org.opencontainers.image.revision=abc1234 -t expose-demo2 .
$ docker image inspect expose-demo2 --format '{{index .Config.Labels "org.opencontainers.image.revision"}}'
abc1234

Labels are also filters. They work on images and, when set with docker run --label, on containers:

CONSOLE
$ docker images --filter label=org.opencontainers.image.version=1.0.0 --format '{{.Repository}}'
expose-demo2
expose-demo
$ docker run -d --name lbl --label env=dev expose-demo
$ docker ps --filter label=env=dev --format '{{.Names}}'
lbl

Compose, Traefik and many monitoring tools use container labels for configuration, so you will see them again in Compose and Nginx and Reverse Proxies.

Do not put secrets in labels. Like ENV, they are readable by anyone who can inspect the image. Old Dockerfiles used MAINTAINER; it is deprecated, use LABEL org.opencontainers.image.authors instead.

STOPSIGNAL: how to ask nicely

When you run docker stop, Docker sends SIGTERM by default, then SIGKILL after the timeout. Some programs prefer a different signal for a graceful shutdown. nginx, for instance, treats SIGQUIT as "finish current requests, then exit". STOPSIGNAL changes what docker stop sends:

DOCKERFILE
STOPSIGNAL SIGQUIT
CONSOLE
$ docker inspect web1 --format '{{.Config.StopSignal}}'
SIGQUIT
$ docker stop web2
$ docker inspect web2 --format 'exit={{.State.ExitCode}}'
exit=0

You can write a name (SIGQUIT, SIGINT) or a number (3). Use it when the app's documentation says graceful shutdown uses a signal other than SIGTERM; otherwise leave the default. Remember that the signal only helps if your program is actually PID 1 and receives it, as explained in CMD and ENTRYPOINT. You can also override it per container with docker run --stop-signal.

A well-formed Dockerfile ending

Putting the lesson together, the last part of a typical application Dockerfile looks like this:

DOCKERFILE
FROM node:lts-alpine
LABEL org.opencontainers.image.title="orders-api" \
      org.opencontainers.image.source="https://example.com/orders.git"

RUN addgroup -S app && adduser -S -G app app
USER app
WORKDIR /app
COPY --chown=app:app package*.json ./
RUN npm ci --omit=dev
COPY --chown=app:app . .

ENV NODE_ENV=production
EXPOSE 3000
CMD ["node", "server.js"]

This is a read-only example (it needs a project to build), but every instruction in it was covered above. The order matters: the files that change least come first, which helps the cache (The Build Cache).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Dockerfile contains EXPOSE 8080. You run docker run -d image and open http://localhost:8080 on the host. What happens?

    EXPOSE is metadata. Publishing needs -p host:container, or -P to publish every exposed port to random host ports.
  2. 2. After USER app, your app cannot create files in /app, which was made by an earlier WORKDIR /app while building as root. What is a clean fix?

    WORKDIR creates a missing directory as the user active at that moment. Switching USER first, or chowning the writable directories, gives the app write access.
  3. 3. What does WORKDIR data do right after WORKDIR /app?

    A relative WORKDIR is resolved against the previous WORKDIR, and the directory is created automatically when missing.
  4. 4. Which is the best way to record the git commit an image was built from?

    The standard OCI label org.opencontainers.image.revision is read by registries and tools, and a build flag keeps the Dockerfile unchanged between commits.
  5. 5. Which statement about STOPSIGNAL is true?

    docker stop sends the stop signal (SIGTERM by default) and falls back to SIGKILL after the timeout. STOPSIGNAL changes only the first signal.

Summary

  • WORKDIR sets the directory for following instructions and for the container's process; it creates missing directories, accepts ENV variables and stacks relative paths. Prefer it over RUN cd.
  • Containers run as root unless you say otherwise. Create an account and switch with USER, ideally with a numeric ID, and make only the directories the app must write to writable by it.
  • A directory created by WORKDIR while still root is root-owned. Use USER before WORKDIR, COPY --chown, or an explicit chown.
  • EXPOSE only documents ports and feeds -P and tooling. Real publishing needs -p; bind to 127.0.0.1 unless the service must be public.
  • LABEL adds searchable metadata. Use reverse-DNS keys and the standard org.opencontainers.image.* names, and keep secrets out.
  • STOPSIGNAL changes the first signal docker stop sends; the program must be PID 1 (or forward signals) to benefit.

Next: HEALTHCHECK