I'm currently moving my backend from polyrepo or multirepo to a monorepo.
I've successfully moved the shared packages into the Lerna monorepo, now it's time for microservices.
My project structure is simple as that:
root
services
service_written_in_node
Dockerfile
package.json
service_Written_in_something_else
Dockerfile
packages
shared_package_1
package.json
shared_package_2
package.json
So basically everything in the directory packages should be published to the npm, and everything in services dir should be published to the Docker registry.
You can use functionality of package.json and add a postinstall script there.
ex.:
"scripts": {
"postinstall": "npm run docker-build-publish",
"docker-build-publish: "docker build .... {ADD HERE SCRIPTS TO PUSHLISH}
}
Have this in each of your services that has a Dockerfile.
At root of repo you can use lerna bootstrap as your postinstall to trigger install on each service.
You can always check other pre and post scripts that can fit better you usecase: https://docs.npmjs.com/cli/v8/using-npm/scripts
I have a projectA that references a common package that my other Nodejs services will reference as well. The issue is how do I pack this up in a Docker file? Ideally, the tsc build would build both the project and the dependent common package into the /dist but that's not the case. (Tried using the prepend but it has to be used on AMD or SYSTEM and cannot be used with node). What are my options to have a shared package in Typescript for multiple Nodejs services and to pack it into a Docker (each service seperately)? I got it working with the project reference (I can use the imports from the shared package) but I dont know how to use the Docker file with this setup.
My docker will look something like this
FROM node:10-alpine
# update packages
RUN apk update
# create root application folder
WORKDIR /app
# copy configs to /app folder
COPY package*.json ./
COPY tsconfig.json ./
# copy source code to /app/src folder
COPY src /app/src
# check files list
RUN ls -a
RUN npm install
RUN npm run build
EXPOSE 7777
CMD [ "node", "./dist/main.js" ]
But with this setup I'll be missing the shared package (project)
root
|-serviceA (has docker file)
|-serviceB (has docker file)
|-shared ( some Mongodb models)
Both depend on shared via references, all three have tconfig
Did you ever find a clean way to do this? My current approach is to run the docker build from the parent directory and copy the common project as well, but that feels messy
I usually write Dockerfiles for Java / Go applications and it's the first time I have encountered a situation where I have to write a Dockerfile for an already existing (and production running) Node.js application. As per my little knowledge about the Node.js which I acquired in the past couple of days, dist folder is generated after we build a Node.js project which carries the source code (please correct me if I am wrong here). So I am interested in copying the dist folder from parent Docker image to child Docker image.
However, after I copy everything from an application into my parent Docker image (line 6) and run 'npm run build' command, dist folder is not generated for me (please note the node_modules and package-lock.json are being generated).
My Dockerfile is as below:
FROM node:10-alpine as BUILD
WORKDIR /src
COPY package*.json /src
RUN apk add --update --no cache \
python \
make \
g++
RUN npm install
COPY . /src
RUN npm run build
How can I resolve this?
If you are using typescript in your node application then follow these instructions.
Please add the below entry under compilerOptions section on "tsconfig.json"
tsconfig.json
**"outDir": "./dist/"**
package.json - Add the below script too.
"scripts": { "build": "tsc" }
Now, re-run the "npm run build". You will see the dist folder.
Try by ignoring the 'tsconfig.tsbuildinfo' file.
don't copy this file into docker container.
I have a node.js+express application. To deploy it to my server the partner is asking me to "build" the app into a folder called "dist" where all the files that need to be deployed to the server will exist. How can I implement such kind of a build.
Any hint or guidance would be appreciated.
You could create a script which does this in your package.json. You simply need to create the directory and copy everything required for running your application in production to it and no more.
//package.json
{
//...
"scripts": {
"dist": "mkdir -p dist && cp -R node_modules src server.js ... dist"
}
//...
}
Not the above is not cross-platform compatible. This is always the complex part of such build scripts. If this is an issue for you, I'd recommend looking at using available tooling such as gulp.
You can also use a NPM lifecycle hook to do this automatically as part of your install. Ensure you also run npm install --production rather than npm install to omit your dev dependencies.
I have a node application that I want to host in a Docker container, which should be straight forward, as seen in this article:
https://nodejs.org/en/docs/guides/nodejs-docker-webapp/
In my project, however, the sources can not be run directly, they must be compiled from ES6 and/or Typescript. I use gulp to build with babel, browserify and tsify - with different setups for browser and server.
What would be the best workflow for building and automating docker images in this case? Are there any resources on the web that describes such a workflow? Should the Dockerimage do the building after npm install or should I create a shell script to do all this and simply have the Dockerfile pack it all together?
If the Dockerfile should do the build - the image would need to contain all the dev-dependencies, which are not ideal?
Note: I have been able to set up a docker container, and run it - but this required all files to be installed and built beforehand.
The modern recommendation for this sort of thing (as of Docker 17.05) is to use a multi-stage build. This way you can use all your dev/build dependencies in the one Dockerfile but have the end result optimised and free of unnecessary code.
I'm not so familiar with typescript, but here's an example implementation using yarn and babel. Using this Dockerfile, we can build a development image (with docker build --target development .) for running nodemon, tests etc locally; but with a straight docker build . we get a lean, optimised production image, which runs the app with pm2.
# common base image for development and production
FROM node:10.11.0-alpine AS base
WORKDIR /app
# dev image contains everything needed for testing, development and building
FROM base AS development
COPY package.json yarn.lock ./
# first set aside prod dependencies so we can copy in to the prod image
RUN yarn install --pure-lockfile --production
RUN cp -R node_modules /tmp/node_modules
# install all dependencies and add source code
RUN yarn install --pure-lockfile
COPY . .
# builder runs unit tests and linter, then builds production code
FROM development as builder
RUN yarn lint
RUN yarn test:unit --colors
RUN yarn babel ./src --out-dir ./dist --copy-files
# release includes bare minimum required to run the app, copied from builder
FROM base AS release
COPY --from=builder /tmp/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./
CMD ["yarn", "pm2-runtime", "dist/index.js"]
One possible solution is to wrap your build procedure in a special docker image. It is often referred as Builder image. It should contain all your build dependencies: nodejs, npm, gulp, babel, tsc and etc. It encapsulates all your build process, removing the need to install these tools on the host.
First you run the builder image, mounting the source code directory as a volume. The same or a separate volume can be used as output directory.
The first image takes your code and runs all build commands.
As a first step you take your built code and pack it into production docker image as you do now.
Here is an example of docker builder image for TypeScript: https://hub.docker.com/r/sandrokeil/typescript/
It is ok to have the same docker builder for several projects as it is typically designed to be general purpose wrapper around some common tools.
But it is ok to build your own that describes more complicated procedure.
The good thing about builder image is that your host environment remains unpolluted and you are free to try newer versions of compiler/different tools/change order/do tasks in parallel just by modifing Dockerfile of your builder image. And at any time you can rollback your experiment with build procedure.
I personally prefer to just remove dev dependencies after running babel during build:
FROM node:7
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Copy app source
COPY src /usr/src/app/src
# Compile app sources
RUN npm run compile
# Remove dev dependencies
RUN npm prune --production
# Expose port and CMD
EXPOSE 8080
CMD [ "npm", "start" ]
Follow these steps:
Step 1: make sure you have your babel dependencies inside of dependencies not dev dependencies on package.json. Also Add a deploy script that is referencing to babel from the node_modules folder. you will be calling this script from within docker
This is what my package.json file looks like
{
"name": "tmeasy_api",
"version": "1.0.0",
"description": "Trade made easy Application",
"main": "build/index.js",
"scripts": {
"build": "babel -w src/ -d build/ -s inline",
"deploy" : "node_modules/babel-cli/bin/babel.js src/ -d build/",
},
"devDependencies": {
"nodemon": "^1.9.2"
},
"dependencies": {
"babel-cli": "^6.10.1",
"babel-polyfill": "^6.9.1",
"babel-preset-es2015": "^6.9.0",
"babel-preset-stage-0": "^6.5.0",
"babel-preset-stage-3": "^6.22.0"
}
}
build is for your development purposes on your local machine and deploy is to be called from within you dockerfile.
Step 2: since we want to do the babael transformation ourselves make sure to add .dockerignore with the build folder that you are using during development.
This is what my .dockerignore file looks like.
build
node_modules
Step 3. Construct your dockerfile. below is a sample of my docker file
FROM node:6
MAINTAINER stackoverflow
ENV NODE_ENV=production
ENV PORT=3000
# use changes to package.json to force Docker not to use the cache
# when we change our application's nodejs dependencies:
ADD package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /var/www && cp -a /tmp/node_modules /var/www
# copy current working directory into docker; but it first checks for
# .dockerignore so build will not be included.
COPY . /var/www/
WORKDIR /var/www/
# remove any previous builds and create a new build folder and then
# call our node script deploy
RUN rm -f build
RUN mkdir build
RUN chmod 777 /var/www/build
RUN npm run deploy
VOLUME /var/www/uploads
EXPOSE $PORT
ENTRYPOINT ["node","build/index.js"]
I just released a great seed app for Typescript and Node.js using Docker.
You can find it on GitHub.
The project explains all of the commands that the Dockerfile uses and it combines tsc with gulp for some added benefits.
If you don't want to check out the repo, here's the details:
Dockerfile
FROM node:8
ENV USER=app
ENV SUBDIR=appDir
RUN useradd --user-group --create-home --shell /bin/false $USER &&\
npm install --global tsc-watch npm ntypescript typescript gulp-cli
ENV HOME=/home/$USER
COPY package.json gulpfile.js $HOME/$SUBDIR/
RUN chown -R $USER:$USER $HOME/*
USER $USER
WORKDIR $HOME/$SUBDIR
RUN npm install
CMD ["node", "dist/index.js"]
docker-compose.yml
version: '3.1'
services:
app:
build: .
command: npm run build
environment:
NODE_ENV: development
ports:
- '3000:3000'
volumes:
- .:/home/app/appDir
- /home/app/appDir/node_modules
package.json
{
"name": "docker-node-typescript",
"version": "1.0.0",
"description": "",
"scripts": {
"build": "gulp copy; gulp watch & tsc-watch -p . --onSuccess \"node dist/index.js\"",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Stephen Gardner (opensourceaugie#gmail.com)",
"license": "ISC",
"dependencies": {
"express": "^4.10.2",
"gulp": "^3.9.1",
"socket.io": "^1.2.0"
},
"devDependencies": {
"#types/express": "^4.11.0",
"#types/node": "^8.5.8"
}
}
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"declaration": false,
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "ES6"
},
"include": [
"**/*.ts"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
To get more towards the answer of your question -- the ts is being compiled from the docker-compose.yml file's calling of npm run build which then calls tsc. tsc then copies our files to the dist folder and a simple node dist/index.js command runs this file. Instead of using nodemon, we use tsc-watch and gulp.watch to watch for changes in the app and fire node dist/index.js again after every re-compilation.
Hope that helps :) If you have any questions, let me know!
For the moment, I'm using a workflow where:
npm install and tsd install locally
gulp build locally
In Dockerfile, copy all program files, but not typings/node_modules to docker image
In Dockerfile, npm install --production
This way I get only the wanted files in the image, but it would be nicer if the Dockerfile could do the build itself.
Dockerfile:
FROM node:5.1
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Bundle app
COPY package.json index.js /usr/src/app/
COPY views/ /usr/src/app/views/
COPY build/ /usr/src/app/build/
COPY public/ /usr/src/app/public/
# Install app dependencies
RUN npm install --production --silent
EXPOSE 3000
CMD [ "node", "index.js" ]
I guess a complete automation in the "imaging process" could be established by building in the Dockerimage script and then deleting the unwanted files before installing again.
In my project, however, the sources can not be run directly, they must be compiled from ES6 and/or Typescript. I use gulp to build with babel, browserify and tsify - with different setups for browser and server. What would be the best workflow for building and automating docker images in this case?
When i understand you right, you want to deploy your web app inside a Docker container and provide different flavours for different target-environments (you mentioned different browser and server). (1)
If the Dockerfile should do the build - the image would need to contain all the dev-dependencies, which are not ideal?
It depends. If you want to provide a ready-to-go-image, it has to contain everything your web app needs to run. One advantage is, that you later only need to start the container, pass some parameters and you are ready to go.
During the development phase, that image is not really necessary, because of your usually pre-defined dev-environment. It costs time and resources, if you generate such an image after each change.
Suggested approach: I would suggest a two way setup:
During development: Use a fixed environment to develop your app. All software can run locally or inside a docker/VM. I suggest using a Docker container with your dev-setup, especially if you work in a team and everybody needs to have the same dev-basement.
Deploy Web app: As i understood you right (1), you want to deploy the app for different environments and therefore need to create/provide different configurations. To realize something like that, you could start with a shell-script which packages your app into different docker container. You run the script before your deploy. If you have Jekyll running, it calls your shell-script after each commit, after all tests ran fine.
Docker container for both development and deploy phase: I would like to refer to a project of mine and a colleague: https://github.com/k00ni/Docker-Nodejs-environment
This docker provides a whole development- and deploy-environment by maintaining:
Node.js
NPM
Gulp
Babel (auto transpiling from ECMA6 to JavaScript on a file change)
Webpack
and other JavaScript helpers inside the docker container. You just link your project folder via a volume inside the docker container. It initializes your environment (e.g. deploys all dependencies from package.json) and you are good to go.
You can use it for development purposes so that you and your team are using the same environment (Node.js version, NPM version,...) Another advantage is, that file changes lead to a re-compiling of ECMA6/ReactJS/... files to JavaScript files (No need to do this by hand after each change). We use Babel for that.
For deployment purposes, just extend this Docker image and change required parts. Instead of linking your app inside the container, you can pull it via Git (or something like that). You will use the same basement for all your work.
I found this article that should guide you in both development and production phases: https://www.sentinelstand.com/article/docker-with-node-in-development-and-production
In this article we'll create a production Docker image for a
Node/Express app. We'll also add Docker to the development process
using Docker Compose so we can easily spin up our services, including
the Node app itself, on our local machine in an isolated and
reproducable manner.
The app will be written using newer JavaScript syntax to demonstrate
how Babel can be included in the build process. Your current Node
version may not support certain modern JavaScript features, like
ECMAScript modules (import and export), so Babel will be used to
convert the code into a backwards compatible version.