Build and Deploy a ReactJS App to AWS EC2 with Docker, NGINX, and Automate with GitHub Actions.
Published: 2024-01-05 20:40:00

In today’s digital landscape, master the art of building, deploying and automating ReactJS Apps using Docker, NGINX and GitHub actions on AWS EC2. Dive into this comprehensive guide and transform your coding journey into an adventure of innovation, efficiency and cutting-edge technologies.

Table of Contents

1. Prerequisites
2. Setting Up the Project
3. Dockerizing the ReactJS application
4. Setting up NGINX
5. Automating deployment with GitHub Actions on AWS EC2


**1. Prerequisites**
Before diving into this project, which involves several technologies and concepts, you need a solid grounding in the following areas to ensure successful learning and implementation such as:

**Basic Web development**: A good understanding of HTML, CSS and JavaScript is essential, as ReactJS is a JavaScript library for building user interfaces.

**Git and version control**: A good knowledge of Git and version control concepts will help you manage your code base and collaborate effectively.

**Docker**: Understanding containerization for docker is crucial to packaging your application and its dependencies in isolated containers.

**NGINX**: A basic knowledge of NGINX as a web server and reverse proxy will be necessary to set up the server environment.

Remember, while these requirements are essentials, you don’t need to be an expert in every area. You can learn and develop your expertise as you go along. What’s more, official documentation, online tutorials and communities can provide invaluable support as you learn.

Note that you can find the link of final source code in the build and [deploy-reactApp to-aws ec2 via github-actions repository](https://github.com/kilamaelie/build-and-deploy-reactApp-to-aws-ec2-via-github-actions).

**2. Setting Up the Project**
This involves several steps which including the installation, project structure and other basic configuration, here’s a step-by-step guide helping you get started :

- **Install Node.js and npm**:
Before you begin, make sure Node.js and npm ( Node Package Managers) are installed on your system. You can download them from the official website: 
[https://nodejs.org](https://nodejs.org).

- **Create a New Project**:
Open your terminal and navigate to the directory where you want to create the project, for the purpose of this tutorial we’ll create a directory with a name `react-tutorial-app` or you can name it anything depending on your project name. This folder is considered as the root directory for our application which contains all folders and files structures.

> In software development, “project structure” provides a clear and logical layout that helps developers understand and navigate the codebase more easily. A well-designed project structure promotes maintainability, collaboration, and efficient development.

Then, we will change our directory into the `react-tutorial-app `folder and all other parts of configuration files or folders will be in this folder.

```
> mkdir react-tutorial-app
> cd react-tutorial-app
```

Inside the react-tutorial-app folder, to create a new React project runs the following command using `create-react-app `and for more details on how create-react-app works and other staff, please visit the official website: [https://create-react-app.dev/](https://create-react-app.dev/)

```
npx create-react-app your-app-name # website is our app-name or folder name 
```

`create-react-app` is a command-line tool that allows you to quickly and easily set up a new **Reactjs** Application, this boilerplate setup generates a basic project structure, including essential files and configuration needed to start building a React application .

Let’s change the directory into `website` as our app-name for React application.

```
cd website # app-name 
```

To start the development server and preview your React app, use the following command:

```
npm start
```

> This command will initiate the development server, which will compile your React code, bundle assets, and start a local web server to serve your application. It will also open your app in your default web browser automatically.

Once the development server is up and running, you can access your React app by visiting `http://localhost:3000` in your web browser. So well done 👏 for creating a React application and setting up the project.

**3. Dockerizing the ReactJS application**
Docker provides a standardized way to package and distribute applications, making it easier to deploy and manage across different environments. In this section, we’ll containerize our ReactJS application using Docker.


> _If you haven’t already, install Docker on your machine by following the instructions for your operating system: [https://docs.docker.com/get-docker/](https://docs.docker.com/get-docker/)_

In your React app’s root directory, create a file named `Dockerfile`. This file defines the instructions to build your Docker image.

```
# Use an official Node.js runtime as the base image

FROM node:19.6.0-alpine
# Set the working directory within the container
WORKDIR /website

# Copy package.json and package-lock.json to the container
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application code to the container
COPY . .

# Build the React app
EXPOSE 3000
```

Since in this project will have more than one container , then we ‘ll need to use `docker-compose`

**Docker-compose** : allows you to define and run multiple Docker containers as a single service, making it easier to manage complex applications.


> _If you haven’t already, you’ll need to install Docker Compose. Follow the installation instructions for your operating system: [https://docs.docker.com/compose/install/](https://docs.docker.com/compose/install/)_


In your project’s root directory as `react-tutorial-app`, create a file named `docker-compose.yml`. This file will contain the configuration for your multi-container application.

```
version: '3'
services:
  website:
    build:
      context: ./website
      dockerfile: Dockerfile
    command: npm start
    ports:
      - "3000:3000"
```

This defines only one service website but a bit later more will be added. So in order to test it, just go in your terminal, navigate to the directory containing the `docker-compose.yml` file and run:

```
docker-compose up
```

Docker Compose will build the required images and start the defined containers. You’ll see logs from both services in the terminal and also depending on your configuration, you can access your ReactJS app at `http://localhost:3000` . Kill the task in the terminal where `docker-compose up `is running in order to stop the. To remove the containers and their associated resources, run:

```
docker-compose rm -v
```

**4. Setting up NGINX**
NGINX is a reverse proxy to serve the built static files of your React application. This setup is commonly used to improve performance and manage routing in production environments.

In the root of your project directory, create a Nginx directory named nginx then create a configuration file named `nginx.conf` . So inside **nginx.conf** file adds the following configuration:

```
server {
     listen 80;
     server_name localhost; 
     #server_name can add your domain or Ip address for your server in the production
 
     location / {
         root /usr/share/nginx/html/website;
         try_files $uri $uri/ /index.html;
     }
 }
```

In the same directory as your Nginx, create a `Dockerfile` which defines how to build a custom Nginx Docker Image:

```
# Use an official Nginx image as the base image
FROM nginx:latest

# Remove any existing config files
RUN rm /etc/nginx/conf.d/*

# Copy the custom Nginx configuration
COPY nginx.conf /etc/nginx/conf.d/

# Expose port 80 for Nginx
EXPOSE 80
```

Before testing in development, let’s update our `docker-compose `file by adding the Nginx service

```
version: '3'
services:
website:
  build:
    context: ./website
    dockerfile: Dockerfile
  volumes:
   - website:/website/build/  # build files will be added at this directory !!!

nginx:
  build:
   context: ./nginx
   dockerfile: Dockerfile
  ports:
    - "80:80"
  volumes:
     - website:/usr/share/nginx/html/website # Copy React App's build files to the Nginx directory

volumes:
   website:
```

And also update the `Dockerfile` for the react app in the website directory

```
# Use an official Node.js runtime as the base image

FROM node:19.6.0-alpine
# Set the working directory within the container
WORKDIR /website

# Copy package.json and package-lock.json to the container
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application code to the container
COPY . .

# Build the React app
RUN npm run build

# Build the React app
EXPOSE 3000
```

For the purpose of testing if everything works, we’ll open a terminal and navigate to your `root` directory. Run the following command:

```
docker-compose up  # 
```
Then let’s testing at [http://localhost:80](http://localhost:80) or [http://127.0.0.1:80](http://127.0.0.1:80)

Kill the task in the terminal where the container is running. To remove the container and its associated resources, run:

```
docker-compose rm -v
```

Then, let’s create `docker-compose.ci` and `docker-compose.prod `files for the production and workflow purpose in the root directory of the project

`Docker-compose.ci
`

```
version: '3'
services:
  website:
    build:
      context: ./website
      dockerfile: Dockerfile
    cache_from:
        - '${WEBSITE_IMAGE}'
    image: '${WEBSITE_IMAGE}'
    ports:
      - "3000:3000"
    volumes:
      - website:./website/build/  # build files will be added at this directory !!!

  nginx:
    build:
     context: ./nginx
     dockerfile: Dockerfile
    cache_from:
        - '${NGINX_IMAGE}'
    image: '${NGINX_IMAGE}'
    ports:
      - "80:80"
    volumes:
      - website:/usr/share/nginx/html/website # Copy React App's build files to the Nginx directory
```

`Docker-compose.prod`

```
version: '3'
services:
  website:
    container_name: 'website'
    image: '${WEBSITE_IMAGE}'
    ports:
      - "3000:3000"
    volumes:
      - website:./website/build/  # build files will be added at this directory !!!
  
  nginx:
    container_name: 'nginx'
    image: '${NGINX_IMAGE}'
    ports:
      - "80:80"
    volumes:
      - website:/usr/share/nginx/html/website # Copy React App's build files to the Nginx directory

volumes:
  website:
```
So for this tutorial will use Github packages for hosting the images.

[GitHub Package Registry](https://github.com/features/packages) is a package hosting service provided by GitHub. It allows you to publish, share, and manage software packages directly within your GitHub repositories.

It lets you host your software, either publicly or privately, for use in your projects on GitHub.


**AWS Setup**

Let’s start by setting up an EC2 instance to deploy our application. To do this, and you’ll need to open an [AWS](https://aws.amazon.com/) account (if you don’t already have one).

> If you don’t know how to set up AWS EC2 , please visit this link which will guide you through how to :[ launch EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html)

Once we’ve finished configuring AWS EC2 and the instance is up and running, we can install Docker on it.

So connect via SSH into the instance using your Key Pair as :

```
$ ssh -i your-key-pair.pem ec2-user@<PUBLIC-IP-ADDRESS>

#example 
# ssh -i ~./ssh/react-tutorial.perm ec2-user@54.201.189.94

```

After accessing the instance, start by updating the server package and installing the latest version of `Docker` and `Docker-compose`:

```
[ec2-user]$ sudo yum update -y
[ec2-user]$ sudo yum install -y docker
[ec2-user]$ sudo service docker start
[ec2-user]$ sudo curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
[ec2-user]$ sudo chmod +x /usr/local/bin/docker-compose

[ec2-user]$ docker --version
Docker version 20.10.23, build 7155243

[ec2-user]$ docker-compose --version
Docker Compose version v2.18.1
```

Add the `ec2-user` to the `docker group` so that you can use it without running the Docker command with sudo :

```
[ec2-user]$ sudo usermod -a -G docker ec2-user
```

Next, let’s generate the SSH KEY

```
[ec2-user]$ ssh-keygen -t rsa
```

> _Please! save the Key without setting any password_

Next, copy the public key into the `authorized_keys` file and set the appropriate authorizations.:

```
[ec2-user]$ cat ~/.ssh/id_rsa.pub 
# Copy this public key into ~/.ssh/authorized_keys
[ec2-user]$ vi ~/.ssh/authorized_keys
# After adding the public key into authorized_key then exits  from vi text editor 
# Then add these commands are used to change the permissions of these files 
[ec2-user]$ chmod 600 ~/.ssh/authorized_keys
[ec2-user]$ chmod 600 ~/.ssh/id_rsa
```
Now, copy the contents of the private key

```
[ec2-user]$ cat ~/.ssh/id_rsa

# Copy the private key somewhere for later use
```


**5. Automating Deployment with GitHub Actions to AWS EC2
**

It is an integrated continuous integration and continuous deployment (CI / CD) platform provided by GitHub .

Since our workflow will use GitHub’s core features (GitHub packages), GitHub requires you to create an access token, which will be used as a GitHub user ID for all your interactions.

Go to the [Personal access tokens](https://github.com/settings/tokens) area in the Developer settings of your GitHub profile and click Generate new token.

![personal access tokens](https://res.cloudinary.com/dwz5lx2k7/image/upload/v1692573249/tutorials/Screenshot_2023-08-18_at_2.07.04_AM_hf5elq.webp)

To configure[ GitHub Actions](https://docs.github.com/en/actions), start by adding a new directory called `.github` to the root of your project, then within this directory, add another directory called `workflows` . Now to configure the workflow, which is a set of one or more jobs, create a new file in the workflows directory called `main.yml` . You can also run the following command in your root directory.

```
mkdir .github && cd .github
mkdir workflows && cd workflows
touch main.yml
```

`main.yml`
{% embed https://gist.github.com/kilamaelie/d08bd6493e8b4a430bf5ca2f166ac6ad %}

So, in the `main.yml` we define :

1. set the environment variables
2. Three jobs to run:

a. build job consist of:

Set various environment variables
Login in the Github package by using the PERSONAL_ACCESS_TOKEN created
Pull images for caching, build the images and push to Github Registry

b. checking-secret consist of :

checking if the deploy variables are existing

> _Notes about the secrets_

- secrets.PERSONAL_ACCESS_TOKEN
- secrets.NAMESPACE
- secrets.PRIVATE_KEY
- secret.AWS_EC2_IP_ADDRESS
- secrets.AWS_HOST_USER

All of the secrets need to be set in your repository’s [secrets ](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions#creating-encrypted-secrets)(Settings > Secrets) and use your Github username or your organization name as your NAMESPACE and your personal access token as PERSONAL_ACCESS_TOKEN .

c. deploy job consist of:

- Add the environment variable to .env file which will be created on the AWS EC2 instance.
- Add the private key to ssh-agent for password less.
- Deploy the build the images on AWS EC2 instance.

Once you are done, commit and push your code to the Github to trigger the workflow to run, so now you should see the images in the Github Packages.

> _Please make sure your on main branch because the workflow’s can only trigger on the main branch other you can it to your preferences._

Workflow successfully finished :
![workflow](https://res.cloudinary.com/dwz5lx2k7/image/upload/v1692573249/tutorials/Screenshot_2023-08-18_at_2.07.04_AM_hf5elq.webp)


Once all our jobs have been executed, navigate to the IP of your instance, and you should see the React application running :
![react-app](https://res.cloudinary.com/dwz5lx2k7/image/upload/v1692573250/tutorials/Screenshot_2023-08-18_at_2.05.55_AM_rojn4g.webp)

👏 And there you have it, this guide has equipped you with the skills you need to successfully build, deploy and automate ReactJS applications using Docker, NGINX and GitHub Actions on AWS EC2. Keep exploring, stay curious and keep building on this foundation to create even more sophisticated and powerful projects. Happy coding!

Thanks for reading through and I hope you liked what you read here. Feel free to connect with me on[ LinkedIn](https://www.linkedin.com/in/kilamaelie/), [twitter](https://twitter.com/kilamaelie) and [GitHub](https://github.com/kilamaelie).