Skip to content

Instantly share code, notes, and snippets.

@d3vAdv3ntur3s
Last active August 4, 2021 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d3vAdv3ntur3s/3c082c775a934ce5b1100297d9b198d7 to your computer and use it in GitHub Desktop.
Save d3vAdv3ntur3s/3c082c775a934ce5b1100297d9b198d7 to your computer and use it in GitHub Desktop.
Node Docker Best Practices and mounting secret

Docker Build command

id - this has to match the id from the mount secret command src - path to file locally docker build --no-cache . -t test-backend --secret id=npmrc,src=backend/.npmrc --file backend/dockerfile

## Mount secrets commannd Part of the docker build kit, enabled by default A way of securely mounting secrets The secret will not be in the final image, one to use for example performing the command npm ci.

RUN --mount=type=secret,mode=0644,id=npmrc,target=/usr/src/app/.npmrc npm ci --only-production
# Multi stage dockerfile to build only production assets and ignoring non-nessesary files in copy via dockerignore
# Stage 1
FROM node:14-alpine@sha256:0c80f9449d2690eef49aad35eeb42ed9f9bbe2742cd4e9766a7be3a1aae2a310 AS build
WORKDIR /usr/src/app
COPY package*.json /usr/src/app/
# Secret mount and run command
RUN --mount=type=secret,mode=0644,id=npmrc,target=/usr/src/app/.npmrc npm ci --only-production
# Stage 2
FROM node:14-alpine@sha256:0c80f9449d2690eef49aad35eeb42ed9f9bbe2742cd4e9766a7be3a1aae2a310
ENV NODE_ENV production
# Built in user from node alpine image to avoid privlidge escalation
USER node
WORKDIR /usr/src/app
# Change ownership to a node user non-root privliges,
COPY --chown=node:node --from=build /usr/src/app/node_modules /usr/src/app/node_modules
COPY --chown=node:node . /usr/src/app
# Execform notation, which directly spawns a process without wrapping it in a shell. Any signals sent to the container are directly sent to the process
CMD ["node", "server.js"]
//To deal with exit signals and shutdown gracefully
const shutdown = () => {
console.log('Stopping ...');
server.close(() => {
console.log('Stopped');
});
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment