Skip to content

Instantly share code, notes, and snippets.

@adrienjoly
Last active October 23, 2022 12:34
Show Gist options
  • Save adrienjoly/89639c65cbb1b7f0f5eacd2285a78d43 to your computer and use it in GitHub Desktop.
Save adrienjoly/89639c65cbb1b7f0f5eacd2285a78d43 to your computer and use it in GitHub Desktop.
`Dockerfile` to containerize a server from a Node.js/TypeScript monorepo, using Yarn 3 and Turborepo 1.4. Layers are optimized to reduce rebuild time, using the host's `.yarn` cache.
# Build from project root, with:
# $ docker build -t myorg-api-server .
# pruner stage: Only keep the source code that needs to be built
FROM node:16.16-alpine AS pruner
WORKDIR /app
COPY packages/ packages/
COPY .yarnrc.yml package.json turbo.json yarn.lock .
RUN npx [email protected] prune --scope='@myorg/api-server' --docker
# builder stage: Transpile TypeScript code into JavaScript
FROM node:16.16-alpine AS builder
WORKDIR /app
COPY .yarnrc.yml .
COPY .yarn/plugins/ .yarn/plugins/
COPY .yarn/releases/ .yarn/releases/
COPY yarn.lock .
COPY --from=pruner /app/out/json/ .
RUN --mount=type=bind,source=.yarn,target=.yarn,rw yarn install
COPY --from=pruner /app/out/full/ .
RUN yarn turbo run build --filter='@myorg/api-server'...
# cleaner stage: Only keep the files needed to run the server in production
FROM builder AS cleaner
WORKDIR /app
COPY --from=pruner /app/out/yarn.lock .
RUN yarn workspaces focus '@myorg/api-server' --production
RUN yarn cache clean --all
RUN find node_modules -name "*.d.ts" -or -name "*.d.ts.map" -or -name "*.md" -delete
RUN find packages -name "src" -exec rm -rf {} \; || true
RUN find . -name ".turbo" -exec rm -rf {} \; || true
RUN find . -name ".cache" -exec rm -rf {} \; || true
# runner stage: Prepare a secure execution environment to run the server in production
FROM node:16.16-alpine AS runner
WORKDIR /home/node/app
RUN chown node /home/node/app
USER node
COPY --chown=node:node --from=cleaner /app/ .
WORKDIR /home/node/app/packages/api-server
CMD node --conditions=transpiled ./dist/bin/start.js
@aboozaid
Copy link

Is this can be used in dev as well as prod environments? can you please share docker-compose file

@adrienjoly
Copy link
Author

@aboozaid This Dockerfile has been used for production. It can also be used for development. It does not require a docker-compose file to work, and I cannot provide the one we were using because I do not work for that company anymore. Feel free to write your own, based on your needs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment