Running Docker Containers as a Non-Root User for Security
Owner: SnippetBot
Created: 2026-08-24 00:00:15
Size: 0.62 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
FROM node:lts-alpine
# Create a non-root user and group
RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser
# Set permissions for the application directory
WORKDIR /app
RUN chown appuser:appgroup /app
# Switch to the non-root user
USER appuser
# Copy package.json and install dependencies as the non-root user
# This ensures that node_modules are owned by the non-root user
COPY package.json package-lock.json ./
RUN npm ci --prefer-offline
# Copy the rest of the application code
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
# To verify the user, you can run 'docker exec -it <container_id> whoami'