Host an Angular App, ExpressJS endpoint on a AWS EC2 server - angularjs

First of all, I would inform the readers that I am pretty new in NodeJS, Angular and Express.
I have partially completed a project, where I am needed to create a Website in AngularJS with a server side logic(ExpressJS).
But while developing I realised that hosting or deploying a MEAN stack isn't as straightforward like LAMP stack.
So i request a solution to the following problem,
I want to host a website developed in Angular with the endpoint in ExpressJS and database in MySQL.
I have tried to find solutions to this. But none of them painted a clear picture in front of me.
Sadly, the server i have is a free tier due to budget constraints and its a plain simple Ubuntu 18.04 System.
Here is one link that i tried to understand but is for azure.
This one was kind of more helpful but again it raised many questions.
Since I am new to this technology I would be grateful if somebody would help me through the deployment process of Angular and Express together on the same server.

I would go with Docker. One container running a node image and another container running mysql image. The node container will run your angular and express app. Also with Docker you will have no difference between your developing environment and your production environment.
Do you have Docker installed? Which OS are you using?
Download node image from Docker Hub:
docker pull node
Then i would create a Dockerfile to generate an image from node image while copying all your source code on it.
FROM node:latest
LABEL author="Your Name"
ENV NODE_ENV=production PORT=3000
COPY . /app
WORKDIR /app
RUN npm install
EXPOSE $PORT
ENTRYPOINT ["npm", "start"]
The COPY command will copy the source code of your current directory (.) to the app directory inside the container. WORKDIR will set the context where your commands will be executed inside the container so you can run npm install where your package.json is. RUN will download all app dependencies inside the container. ENTRYPOINT will execute the file that will start your app as specified in your package.json file, like below:
"name": "app",
"version": "1.0.0",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"license": "ISC",
"dependencies": { ... }
.dockerignore file (so you do not copy your node modules, Dockerfile, etc inside your container):
node_modules
npm-debug.log
Dockerfile*
docker-compose*
.dockerignore
.git
.gitignore
README.md
LICENSE
.vscode
To create an image based on the above Dockerfile (you need to place Dockerfile and run docker build in the same folder of your app container):
docker build -t image_name .
To run your image in a Docker container:
docker run -d -p 3000:3000 image_name
Running the container like this you can open your app in the browser with your DOCKER_HOST_IP:PORT and it will run your app.
Assuming you are running your app in PORT 3000, we are mapping external 3000 port to the internal port 3000 inside the container where your app is running.
EXPRESS
In order for express to serve your files, you need to set express.static:
// serve client side code.
app.use('/', express.static('app_folder'));

You can git clone your app on EC2 instance and then install a systemd service, here's an example of a service file:
[Unit]
Description=My App
After=syslog.target network.target
[Service]
Environment=NODE_ENV=production
ExecStart=/usr/bin/node /home/appuser/repo-app/index.js
WorkingDirectory=/home/appuser/repo-app/
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myapp
User=appuser
Group=appuser
[Install]
WantedBy=multi-user.target
You can also make a good use of a haproxy in front of your express endpoint.

Related

React hot reload doesn't work in docker container

I am trying to set up React with docker, but for some reason I cannot get the hot reload to work. Currently, if I create a file it recompiles, but if I change something in a file it does not. Also, I didn't change any packages or configuration files, the project was generated with npx create-react-app projectname --template typescript.
From researching this online I found out that I needed to add CHOKIDAR_USEPOLLING=true to a .env file, I tried this but it didn't work, I tried placing the .env in all directories in case I placed it in the wrong one. I also added it to the docker-compose.yml environment.
In addition to this, I also tried downgrading react-scripts to 4.0.3 because I found this, that also didn't work.
I also tried changing a file locally and then checking if it also changes inside the docker container, it does, so I'm pretty sure my docker related files are correct.
Versions
Node 16.14
Docker Desktop 4.5.1 (Windows)
react 17.0.2
react-scripts 5.0.0
Directory structure
project/
│ README.md
│ docker-compose.yml
│
└───frontend/
│ Dockerfile
│ package.json
│ src/
│ ...
Dockerfile
FROM node:16.14-alpine3.14
WORKDIR /app
COPY package.json .
COPY package-lock.json .
RUN npm install
CMD ["npm", "start"]
docker-compose.yml
services:
frontend:
build: ./frontend
ports:
- "3000:3000"
volumes:
- "./frontend:/app"
- "/app/node_modules"
environment:
CHOKIDAR_USEPOLLING: "true"
If you are on Windows and use react-scripts 5.x.x or above, CHOKIDAR_USEPOLLING is not working. Make changes your package.json instead in the following way:
"scripts": {
...
"start": "WATCHPACK_POLLING=true react-scripts start",
...
}
The Dockerfile you have is great for when you want to package your app into a container, ready for deployment. It's not so good for development where you want to have the source outside the container and have the running container react to changes in the source.
What I do is keep the Dockerfile for packaging the app and only build that, when I'm done.
When developing, I can often do that without a dockerfile at all, just by running a container and mapping my source code into it.
For instance, here's a command I use to run a node app
docker run -u=1000:1000 -v $(pwd):/app -w=/app -d -p 3000:3000 --rm --name=nodedev node bash -c "npm install && npm run dev"
As you can see, it just runs a standard node image. Let me go through the different parts of the command:
-u 1000:1000 1000 is my UID and GID on the host. By running the container using the same ids, any files created by the container will be owned by me on the host.
-v $(pwd):/app map the current directory into the /app directory in the container
-w /app set the working directory in the container to /app
-d run detached
-p 3000:3000 map port 3000 in the container to 3000 on the host
--rm remove the container when it exits
-name=nodedev give it a name, so I can kill it without looking up the name
at the end there's a command for the container bash -c "npm install && npm run dev" which starts by installing any dependencies and then runs the dev script in the package.json file. That script starts up node in a mode, where it hot reloads.
Polling wasn't my issue -- watching the docker output I saw it recompiled correctly. My problem was related to networking in the hot loader. I found that the browser is trying to open a websocket back to the node server to ws://localhost:3000/sockjs-node but whatever network settings are like on my computer, this wouldn't route back to the docker container. I added
WDS_SOCKET_HOST=127.0.0.1
to the environment variables. After restarting, the browser successfully connects to ws://127.0.0.1:3000/sockjs-node and hot reloading works properly.
This was tied to using a docker-compose solution similar to the original post. I was able to also make things with with a variation on the docker run approach, but it was much slower to launch.
WSL Workaround for CRA 5.0+
watch.js
const fs = require('fs');
const path = require('path');
if (process.env.NODE_ENV === 'development') {
const webPackConfigFile = path.resolve('./node_modules/react-scripts/config/webpack.config.js');
let webPackConfigFileText = fs.readFileSync(webPackConfigFile, 'utf8');
if (!webPackConfigFileText.includes('watchOptions')) {
if (webPackConfigFileText.includes('performance: false,')) {
webPackConfigFileText = webPackConfigFileText.replace(
'performance: false,',
"performance: false,\n\t\twatchOptions: { aggregateTimeout: 200, poll: 1000, ignored: '**/node_modules', },"
);
fs.writeFileSync(webPackConfigFile, webPackConfigFileText, 'utf8');
} else {
throw new Error(`Failed to inject watchOptions`);
}
}
}
package.json
"scripts": {
"start": "node ./watch && react-scripts start",
I had same issue once, This issue was in my Dockerfile The workdir was /var/app/ while in my docker-compose.yml I mounted current working directory to /var/app/frontend, I just removed that /frontend and works fine. please check yours. thanks
Make sure you use --legacy-watch tag in package.json file
{
"name": "history",
"version": "1.0.0",
"description": "",
"main": "./src/index.js",
"scripts": {
"start": "node ./src/index.js",
"start:dev": "nodemon --legacy-watch ./src/index.js"
},
I had the same issue, and my mistake was that I was editing on my local machine and was expecting code reload inside the docker container. Since 2 of them are at different locations - it will never work out and I had to restart the docker-compose again and again.
Later I used the vscode command palette
"Attach to Running Container..."
option and the selected required container and cd into my code folder and made changes and live reload (or apply code changes on the refresh page) started working.
This helped me solve one issue, the next issue is to use the local ssh-key inside the docker container such that I can do my git sync inside the container itself.
Setting the NODE_ENV="development" in the Dockerfile enables the hot reload

Unable to access react app running in docker container

I have seen this question asked different ways on SO. However, I have not been able to find an answer that works for me. Perhaps I haven't done the right search. So here I go. I'm brand new to docker and have deployed a simple react app using docker. I am able to hit the react app when I run it locally on my host, but when I try to access it from the host while running in the container, my luck runs out.
I understand that the issue is that the container is listening on its loopback interface, but it should listen on all intefaces (0.0.0.0). My issue is that I am not sure how to do that. I've seen instructions on how to do it for a node js app, for python http.server, etc. But not for a react app.
My app is super straightforward. I've created an app using create-react-app. I am able to run it locally and see the react page (http://localhost:3000). I've create a standard Dockerfile for a react app:
FROM node:12.15.0-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD [ "npm", "start" ]
I then built and ran it using the following commands:
docker build -t sampleapp .
docker run -p 3000:3000 -d sampleapp
And as mentioned am not able to see the app on http://localhost:3000
Any help would be ver appreciated. Thanks in advance.
Try adding this to your .env.development
PORT=3000
If you don't have .env.development then make it and add this env var and see if it works.

Why heroku app is serving my source files?

Why my heroku app is serving app directory? This directory and it's files should not appear like you see in the picture. Should display only static directory.
I use rimraf npm package to remove sourcemaps (.map files) and when I use serve -s build command it works properly on localhost, it displays only the static directory. But when I deploy my files to heroku using heroku/nodejs buildpack it serves the files like in the picture.
Important to note: I use just create react app and don't use any http server like express.js
#edit
Ok I know where is the problem. On localhost I use serve -s build and it serves just build directory. When I use npm start on localhost it serves app and build like on the heroku. Because I use npm start on heroku. But how to switch this command to serve? Tried to replace the start script with "start": "serve -s build" but it works only on localhost.
Ok I solved this problem.
Right now I use npm start script which call nodemon ./server.js script which is just express server with get '/*' and send a index.html
No more serve or react-scripts start on production.

Using Docker for create react app without using Nodejs to serve the file

Without using NodeJs to serve the static file, I am trying to build Docker image for create react app with the below folder structure
sampleapp -
client
src
...
DockerFile
So client is build by create-react-app client, the application is just consuming services and rendering it.
Dockerfile:
FROM node:10.15.1-alpine
COPY . /var/panda/client
WORKDIR /var/panda/client
RUN npm install --no-cache && npm run build
EXPOSE 4000
CMD ["npm", "start"]
How can I start the Docker container in local and prod, and is the above Docker script is fine for running the application in production build?
If you're asking how to run an image, you simply do docker build -t client ., and then docker run client. Your Dockerfile is not fine for a prod environment because it runs as root. You should add the following lines just before the last line.
RUN adduser -D user
USER user
Once you've run npm run build you will have a set of static files you can serve. Anything that serves static files will work fine. One typical setup is to use a multi-stage build to first build the application, then serve it out of an Nginx image:
FROM node:10.15.1-alpine AS build
COPY . /var/panda/client
WORKDIR /var/panda/client
RUN npm install --no-cache && npm run build
FROM nginx:1.17
COPY --from=build /var/panda/client/build /usr/share/nginx/html
For day-to-day development, just use the ordinary CRA tools like npm run start directly on your desktop system. You'll get features like live reloading, and you won't have to mess with Docker volumes or permissions. Since the application ultimately runs in the browser it can't participate in things like Docker networking; except for pre-deployment testing there's not really any advantage to running it in Docker.

AngularJS on nginx in Docker container

We have an app written in Angular
We will use an nginx container to host the angular
but the problem is where we have to perform the npm install for creating the /dist folder in angular.
Do we have to perform it in the dockerfile of our nginx-webserver or is this against the rules?
You are obviously using node as your dev server and want to use NGINX as your prod server? We have a similar setup
this is how we do it ...
in our dev environment, we have /dist on .gitignore
on a push to git we have a Jenkins job that does a build (this does the npm install inside a Jenkins build server)
on a successful Jenkins job we do a docker build (a downstream job), the docker build copies the /dist files into the docker image
we then do a docker push
the resulting docker image can be pulled from any server - hope that helps
would welcome your thoughts :)
PS The problem with doing the npm install during the docker build is that your docker container becomes messy. You end up installing loads of software inside it just for setup purposes.
All you really want in your docker image is NGINX serving up your build files.
This is why we do not do an npm install during the docker build.

Resources