Dockerize your Angular NodeJS application

2019-03-31 05:54发布

问题:

We have an front-end application. It's written in Angular (html + css + javascript) which needs to be hosted by a webserver (nginx). Angular is communicating with a NodeJs server which will communicate with the backend.

Now we have to run this in Docker.

  • We want to use 2 Docker containers: one with nodejs and one with nginx and let them work together

So is it possible to write 2 dockerfiles in the one repository? The main idea is to have 1 dockerfile for nodejs which is also running the bower install, npm install, ... which will look like this:

# Create app directory
RUN mkdir -p /usr/src/www
WORKDIR /usr/src/www

RUN npm install -g bower
RUN npm install -g gulp

# Install app dependencies
COPY . /usr/src/www/
RUN bower install
RUN npm install
RUN gulp build

EXPOSE port
CMD [ "node", "server.js" ]

And one dockerfile in which we run a nginx-webserver but will also include a nginx.conf so it can point to the right /dist folder in our node.js-container The dockerfile of nginx will look like this:

# Set nginx base image
FROM nginx

# Copy custom configuration file from the current directory
COPY nginx.conf /etc/nginx/nginx.conf

An example of the nginx.conf

location ~* /dist {
            proxy_pass http://nodejs:port;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;

回答1:

Using 2 docker containers is the best option in my opinion, single responsibility per container design is worth to follow.

It's very common having to create more than one container per project:

  • database
  • backend server
  • frontend server

One approach is create a folder for docker definitions and for each docker context, create an script docker_build.sh that prepares the docker context (copy all the artifacts required: libs, source code, etc) and finally make the docker build.

project_root/
|----src/
|----docker/
|----|----angular/
|----|----|-----Dockerfile
|----|----|-----docker_build.sh
|----|----nodejs/
|----|----|-----Dockerfile
|----|----|-----docker_build.sh       

An example of docker_build.sh

#!/bin/bash

# create temp directory for building
mkdir DockerBuildTempPath/

# copy files to temp directory
cp -arv Dockerfile DockerBuildTempPath/
cp -arv ../../src/ DockerBuildTempPath/
# ... etc

cd DockerBuildTempPath

#build image
docker build -t myapp .

# remove temp directory
cd ..
rm -r ./DockerBuildTempPath/


回答2:

Try jwilder/nginx-proxy(https://github.com/jwilder/nginx-proxy). I'm currently using it to host a main docker Nginx that proxys for all my other docker services.