Deploy Angular Universal application on NGINX Server
Why do you need Angular Universal?
A normal Angular app is rendered in the browser, known as Client-Side-Rendering (CSR). An Angular Universal app is rendered on a server, know as Server-Side Rendering (SSR), which allows your app to be easily found by search engines and web crawlers.
In this article we will cover how to turn a normal Angular app into an Angular Universal app and deploying it to NGINX server with help of docker.
Firstly, we need to install angular in our local machine with the following:
npm install -g @angular/cli
After angular is successfully installed into our machine, then we can go ahead and create a new Angular application using the angular cli:
ng new client
Once the app is generated, then we can serve it by running:
cd client
ng server --open
A new browser window is open, running our app. Now let’s turn our app into a server-side rendering app.
Kill the running process but pressing ctrl + C on your keyboard, then run:
ng add @nguniversal/express-engine
We are done!
Now to test our app we can run the following, then navigate to localhost:4200 in the browser.
npm run dev:ssr
In the root directory of your app add three files:
1. Dockerfile
2. .dockerignore
3. nginx.conf
Open .dockerignore file and add the following:
dist
node_modules
Dockerfile
.dockerignore
.git
.gitignore
Open Dockerfile and add the following:
FROM node:13.10.1 AS build
WORKDIR /app
COPY ./package.json /app/
RUN npm install
COPY . /app/
# this will build the browser and server files:
RUN npm run build:ssrFROM nginx:1.16.1 AS client-browser
COPY — from=build /app/dist/client/browser/ /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.confFROM node:13.10.1-alpine AS ssr-server
COPY — from=build /app/dist /app/dist/
COPY ./package.json /app/package.json
WORKDIR /app
EXPOSE 4000
CMD npm run serve:ssr
Open nginx.conf file and add the following:
server {
listen 4000;location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}# Forward requests to the node container which
# renders on the server side:
location ~ ^/(public)$ {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://127.0.0.1:4000;
}include /etc/nginx/extra-conf.d/*.conf;
}
Now let’s build our docker image by running
docker build -t client .
Our docker image built successfully! Now let’s run our docker image with:
docker run -p 4000:4000 client
Hope this was helpful! 😃