Docker lab/version note: use supported Linux-container tools and patched images. Check version compatibility before running the examples. Docker, Swarm and platform-specific deployment steps were not tested live.
What this guide covers
A container often needs less access than Docker’s defaults provide. A non-root user, read-only application files and resource limits can reduce damage from application mistakes or compromise.
Before you start
Build node-lab:1.0 using the Node.js guide. Use a disposable container named node-hardened. Host administrators and users who control the Docker daemon still have powerful access.
Step 1: Run with explicit restrictions
Run:
docker image inspect node-lab:1.0 --format '{{.Config.User}}'
docker run -d --name node-hardened \
--read-only \
--tmpfs /tmp:rw,noexec,nosuid,nodev,size=16m \
--cap-drop ALL \
--security-opt no-new-privileges=true \
--pids-limit 100 --memory 128m --cpus 0.5 \
--stop-timeout 15 \
-e APP_VERSION=hardened \
-p 127.0.0.1:8082:3000 node-lab:1.0
curl --fail --connect-timeout 3 --max-time 5 http://127.0.0.1:8082/healthz
The main filesystem is read-only; /tmp is a small writable memory filesystem. Capabilities are optional Linux privileges, removed here because this web server does not need them. no-new-privileges prevents gaining additional privileges through program execution.
Step 2: Verify allowed and denied writes
Run:
docker inspect node-hardened --format 'readonly={{.HostConfig.ReadonlyRootfs}} caps={{json .HostConfig.CapDrop}} pids={{.HostConfig.PidsLimit}}'
docker exec node-hardened node -e "console.log('uid='+process.getuid()+' gid='+process.getgid());if(process.getuid()===0)process.exit(1)"
docker exec node-hardened node -e "require('node:fs').writeFileSync('/tmp/probe','ok');console.log('temporary write passed')"
docker exec node-hardened node -e "try{require('node:fs').writeFileSync('/home/node/should-not-write','x');process.exit(1)}catch(e){console.log(e.code);process.exit(e.code==='EROFS'?0:1)}"
The process should not run as root, /tmp should be writable, and an application-directory write should fail. Check the HTTP response too: security flags are not useful if they prevent required application work.
Step 3: Keep only required exceptions
If a real application needs persistent writes, mount only the required directory with suitable ownership. Do not use privileged mode to solve one permission error. Do not mount the Docker socket into an ordinary application. Running as a non-root image user is different from installing a rootless Docker daemon.
Check the result
Confirm the restrictions and application behavior, then stop and remove node-hardened. Keep patching, secrets management, network access and backups in the operating plan; these flags do not replace them.
Conversation
0 commentsNo comments yet. Start the conversation below.