Skip to lesson

Running as a non-root user

ShopLite's container runs as the most powerful user by default, so one bug in the app could rewrite its own jar or the files of a mounted host folder. Running as a normal user limits the damage.

Why root in a container is risky

Root is the all-powerful user with id 0. Inside most images, including eclipse-temurin, every process runs as root unless the Dockerfile says otherwise, and the host kernel knows it as the same uid 0.

Example 1 starts a plain container and asks who it runs as. Example 2 is a program that refuses to start as root.

Example 1 · By default the container runs as root

Runs in: a Linux terminal with Docker installed

Terminal
docker run --rm eclipse-temurin:25-jre id# bind-mount a host folder that does not exist yet, write a file, then look at it on the hostdocker run --rm -v "$PWD/logs":/logs eclipse-temurin:25-jre sh -c 'echo test > /logs/from-container.txt'ls -l logs/from-container.txtrm -f logs/from-container.txt
Sample output
uid=0(root) gid=0(root) groups=0(root)
-rw-r--r-- 1 root root 5 Oct 16 10:42 logs/from-container.txt
rm: cannot remove 'logs/from-container.txt': Permission denied

What this code does

  • id shows uid 0: the JRE image does not set a user, so the process is root.
  • On a Linux host Docker creates the missing logs folder as root, and the file inside belongs to root too, so your own account cannot delete it without sudo. Docker Desktop on Windows and macOS maps file owners differently, so you may not see this there.

Example 2 · An app that refuses to start as root

StartupGuardDemo.javaJava
class StartupGuard {    static void checkUser(String user) {        if (user.equals("root")) {            throw new IllegalStateException("Refusing to start as root: add a USER line to the Dockerfile");        }    }}
public class StartupGuardDemo {    public static void main(String[] args) {        for (String user : new String[] {"root", "spring"}) {            try {                StartupGuard.checkUser(user);                System.out.println(user + ": OK, starting ShopLite");            } catch (IllegalStateException e) {                System.out.println(user + ": " + e.getMessage());            }        }    }}
Output
root: Refusing to start as root: add a USER line to the Dockerfile
spring: OK, starting ShopLite

What this code does

  • A real app would call StartupGuard.checkUser(System.getProperty("user.name")) once in main; here two names are passed in so the output is the same on every computer.
  • Failing fast with a clear message turns a quiet security mistake (a missing USER line) into an error you see on the first run.

Three things go wrong with root. A container-escape bug in Docker or the kernel gives the attacker root on the host. An attacker who breaks into the app can change any file in the container, such as the jar or the CA certificates. And files written to a bind-mounted host folder belong to root on a Linux host, so your normal account cannot even delete them.

Running as a normal user does not fix every bug, but it limits the damage. Security teams and many cloud platforms check for it, and some refuse images that run as root.

Creating a user: groupadd, useradd and USER

USER spring:spring makes every later RUN, and the running container, use the user spring and the group spring. The user must exist in the image first, so you create it with a RUN line.

The Ubuntu-based Temurin images have groupadd and useradd. Alpine images use BusyBox commands instead, as in the snippet below.

Terminal
# Alpine-based image (BusyBox tools)FROM eclipse-temurin:25-jre-alpineRUN addgroup -S spring && adduser -S -G spring springUSER spring:spring

Example 3 · Dockerfile with a spring user (Ubuntu-based JRE)

Runs in: a terminal with Docker installed

Terminal
FROM eclipse-temurin:25-jreRUN groupadd --system spring \    && useradd --system --gid spring --no-create-home --shell /usr/sbin/nologin springWORKDIR /appCOPY target/*.jar app.jarUSER spring:springEXPOSE 8080ENTRYPOINT ["java", "-jar", "/app/app.jar"]# build and check (in the terminal)# docker build -t shoplite-api:1.2.0 .# docker run --rm --entrypoint id shoplite-api:1.2.0
Sample output
uid=999(spring) gid=999(spring) groups=999(spring)

What this code does

  • groupadd and useradd run as root (the default user so far); --system picks a uid below 1000, often 999, with no password and no home folder.
  • COPY happens before USER, so app.jar belongs to root and is read-only for spring. Everything after USER, including the running app, is spring.

--system makes a system account (a uid below 1000) with no password and no login.

Put USER after the steps that need root (installing packages, creating folders) and before ENTRYPOINT. In a multi-stage build only the final stage needs it.

Find the bug

Find the USER mistake

Tap the line that goes wrong.

The build fails with "unable to find user spring". Which line is wrong?

Round 1 of 2

File ownership: COPY --chown and writable folders

COPY --chown=user:group copies files and sets their owner in the same step. Without it, copied files belong to root.

Files from COPY belong to root, so spring can read the jar but not change it. Example 4 gives spring exactly one writable folder.

Example 4 · One writable folder, and the error without it

Runs in: a terminal with Docker installed

Terminal
FROM eclipse-temurin:25-jreRUN groupadd --system spring && useradd --system --gid spring --no-create-home springWORKDIR /appRUN mkdir /app/uploads && chown spring:spring /app/uploads   # only this folder is writableCOPY target/*.jar app.jar                                     # owned by root: read-only for springCOPY --chown=spring:spring config/banner.txt /app/config/     # --chown when spring must change itUSER spring:springENTRYPOINT ["java", "-jar", "/app/app.jar"]# Without the mkdir/chown line, the first product image upload fails:
Sample output
ERROR 1 --- [shoplite-api] [nio-8080-exec-3] c.s.common.GlobalExceptionHandler : Unexpected error
java.nio.file.AccessDeniedException: /app/uploads/product-6.jpg
	at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:90)
	...

What this code does

  • WORKDIR creates /app as root, so spring cannot create new files there. The RUN mkdir ... && chown line gives spring exactly one folder.
  • A real shop would keep uploads in a volume or object storage so they survive a new container; the ownership rule is the same.

For the app's jar that is good: an attacker who gets into the app cannot replace the code. Give spring only the folders it must write to. ShopLite logs to stdout and Tomcat uses /tmp, which every user may write, so it needs none.

If an app writes files, for example uploads, create that one folder and chown it to spring, or mount a volume there.

Predict the output

Who can write there?

The app runs as spring. Pick what happens.

Round 1 of 2

The app tries to overwrite its own jar.

WORKDIR /app
COPY target/*.jar app.jar
USER spring:spring
Avoid chmod -R 777 to "fix" a permission error. It makes every file writable by every user, which is what you were trying to prevent.

Checking: whoami and docker inspect

Two commands show the user: one asks a running container, the other reads the image without starting it.

Terminal
docker inspect --format '{{.Config.User}}' shoplite-api:1.2.0# spring:springdocker exec shoplite-api whoami# springdocker exec shoplite-api id# uid=999(spring) gid=999(spring) groups=999(spring)docker exec shoplite-api touch /app/hacked.txt# touch: cannot touch '/app/hacked.txt': Permission denied

docker exec <container> whoami prints the user that processes in the container run as. docker inspect --format '{{.Config.User}}' <image> reads the USER value stored in the image; an empty answer means root.

Check both after every Dockerfile change. A later USER root line, or a base image that changes its user, can undo your work without any error.

Graceful shutdown: exec form and SIGTERM

Graceful shutdown means the app stops taking new requests, finishes the ones in progress and closes its database pool before it exits, instead of being cut off in the middle of an order.

docker stop asks the app to stop. These settings tell Spring Boot to finish running requests first and how long it may take.

YAML
# application.yml (shoplite-api)server:  shutdown: graceful            # the default since Spring Boot 3.4, written out for clarityspring:  lifecycle:    timeout-per-shutdown-phase: 20s   # default 30s; keep it below docker stop's wait

Example 5 · docker stop with exec form vs shell form

Runs in: a terminal with Docker installed

Terminal
# shoplite-api:1.2.0      ENTRYPOINT ["java", "-jar", "/app/app.jar"]# shoplite-api:shellform  ENTRYPOINT echo "Starting" && java -jar /app/app.jartime docker stop shoplite-apidocker logs --tail 3 shoplite-apitime docker stop shoplite-shelldocker ps -a --format "{{.Names}}: {{.Status}}"
Sample output
shoplite-api
real    0m1.214s
INFO 1 --- [shoplite-api] [ionShutdownHook] o.s.b.w.e.tomcat.GracefulShutdown : Commencing graceful shutdown. Waiting for active requests to complete
INFO 1 --- [shoplite-api] [tomcat-shutdown] o.s.b.w.e.tomcat.GracefulShutdown : Graceful shutdown complete
INFO 1 --- [shoplite-api] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
shoplite-shell
real    0m10.391s
shoplite-api: Exited (143) 14 seconds ago
shoplite-shell: Exited (137) 2 seconds ago

What this code does

  • Exec form: java is PID 1, gets SIGTERM, runs Spring's shutdown hook (thread SpringApplicationShutdownHook, cut to ionShutdownHook in the log) and exits in about a second with 143 = 128 + 15.
  • Shell form: /bin/sh is PID 1 and does not pass SIGTERM on, so Docker waits 10 seconds and sends SIGKILL: 137 = 128 + 9, with no graceful shutdown at all.

Example 6 · A JVM shutdown hook finishing in-flight work

ShutdownHookDemo.javaJava
import java.util.ArrayList;import java.util.List;
class OrderDesk {    private final List<String> inFlight = new ArrayList<>();
    synchronized void accept(String orderId) {        inFlight.add(orderId);        System.out.println("Accepted " + orderId);    }
    synchronized void finishAll() {        for (String orderId : inFlight) {            System.out.println("Finished " + orderId + " before exit");        }        inFlight.clear();    }}
public class ShutdownHookDemo {    public static void main(String[] args) {        OrderDesk desk = new OrderDesk();
        Thread hook = new Thread(() -> {            System.out.println("Shutdown hook: stop taking new orders");            desk.finishAll();            System.out.println("Shutdown hook: closed cleanly");        });        Runtime.getRuntime().addShutdownHook(hook);
        desk.accept("ORD-1041");        desk.accept("ORD-1042");        System.out.println("main() ends; the JVM now runs its shutdown hooks");    }}
Output
Accepted ORD-1041
Accepted ORD-1042
main() ends; the JVM now runs its shutdown hooks
Shutdown hook: stop taking new orders
Finished ORD-1041 before exit
Finished ORD-1042 before exit
Shutdown hook: closed cleanly

What this code does

  • addShutdownHook registers a thread that the JVM starts when it shuts down: when main ends normally, on System.exit, or on SIGTERM from docker stop.
  • Spring Boot registers a hook like this to close the context, which is why SIGTERM must reach java. A hook never runs on SIGKILL (exit 137).

docker stop sends SIGTERM (signal 15) to the container's main process, PID 1, and sends SIGKILL after 10 seconds if the process is still running. With the exec form ENTRYPOINT ["java", "-jar", "app.jar"], java itself is PID 1 and receives it. The JVM then runs its shutdown hooks: code registered with Runtime.getRuntime().addShutdownHook. Spring Boot uses one to close the application context, and with server.shutdown=graceful (the default since Spring Boot 3.4) Tomcat waits for running requests first.

With the shell form ENTRYPOINT java -jar app.jar, PID 1 is /bin/sh. Depending on the shell, java may never get the signal, so Docker waits the full 10 seconds and kills it: exit code 137 instead of 143.

Order of execution

What happens on docker stop

Tap the steps in the order they happen with an exec-form ENTRYPOINT.

docker stop waits 10 seconds by default. Use docker stop -t 30 shoplite-api or docker run --stop-timeout 30 when your app needs longer.

Next step

Check your understanding

12 quick questions