0% found this document useful (0 votes)
3 views19 pages

Configuring A Ubuntu Server For A React Application Using Docker and Nginx

This document provides a comprehensive guide for configuring an Ubuntu server to deploy a React application using Docker and Nginx. It covers initial server setup, user configuration, package installation, firewall configuration, and deployment methods, including obtaining SSL certificates with Certbot. By following the steps outlined, users will establish a secure and scalable environment for their web applications.

Uploaded by

ali.ramdani.dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

Configuring A Ubuntu Server For A React Application Using Docker and Nginx

This document provides a comprehensive guide for configuring an Ubuntu server to deploy a React application using Docker and Nginx. It covers initial server setup, user configuration, package installation, firewall configuration, and deployment methods, including obtaining SSL certificates with Certbot. By following the steps outlined, users will establish a secure and scalable environment for their web applications.

Uploaded by

ali.ramdani.dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Configuring a Ubuntu Server for a

React Application using Docker and


Nginx
Introduction
Initial Ubuntu Server Configuration
Update System Packages
SSH Access Configuration
Configuring SSH Access for Use with an Authentication Key
User Configuration
Granting Superuser (root) Privileges
Installing Packages and Preparing the System
Installing Essential Utilities
Version Management with Git
Setting Up Node.js Environment with NVM
Installing Nginx
Firewall Configuration
Installation and Configuration of Docker Engine
Using Docker
System Preparation Summary
Deploying getechoxen.com with Nginx and Certbot
Prepare the Environment
Obtain SSL Certificates with Certbot

Configuring a Ubuntu Server for a React Application using Docker and Nginx 1
Configure Nginx
Docker Deployment Method
Direct Deployment Method
Test and Reload Nginx
Verify Deployment
Automate Certificate Renewal
Conclusion
Key Takeaways

Introduction
Deploying a web application requires careful planning and configuration to ensure optimal
performance, security, and scalability. This guide will walk you through the process of setting
up and deploying a robust, secure React application on a DigitalOcean droplet using Nginx,
Docker, and Certbot.
We will leverage an Ubuntu server environment to configure a full-stack deployment,
focusing on two methods:

1. Using Docker to encapsulate the React application, providing a consistent and portable
deployment across different environments.

2. Hosting the React application directly from a built folder using Nginx to serve static
content.

Throughout this guide, you’ll learn how to:

Configure an Ubuntu server for optimal security and functionality.

Deploy SSL certificates with Certbot to ensure secure HTTPS connections for your
domain.

Use Docker and Docker Compose to manage application deployment.

Set up Nginx as a reverse proxy to serve your application and distribute content
efficiently with CDN integration.

By the end of this guide, you’ll have a robust deployment strategy for your React application,
ensuring it is secure and scalable, ready to meet varying traffic demands.

Configuring a Ubuntu Server for a React Application using Docker and Nginx 2
💡 Before you begin, make sure you have prepared the following:

A recent Ubuntu server (preferably the latest LTS version)

Sudo privileges or root access to the server

A domain name pointing to your server's IP address

Basic command-line interface (CLI) skills and familiarity with Linux-based


systems

Access to GitHub repositories

Initial Ubuntu Server Configuration


Update System Packages
Keep your server up-to-date with the latest security patches and software versions.

sudo apt update && sudo apt upgrade -y

SSH Access Configuration


To install the OpenSSH server on an Ubuntu system, follow these steps in your Command
Line Interface (CLI):

sudo apt install openssh-server

After installation, the SSH service should start automatically. You can check the status of the
service with the following command:

sudo systemctl status ssh

If the service is not active, you can start it with:

sudo systemctl start ssh

To make it run at startup, use:

Configuring a Ubuntu Server for a React Application using Docker and Nginx 3
sudo systemctl enable ssh

Now you have OpenSSH Server installed and running on your Ubuntu server. You can now
proceed to the recommended security configurations.

Configuring SSH Access for Use with an Authentication Key


Create an SSH key pair (on your local machine):

ssh-keygen -t rsa -b 4096

Follow the on-screen instructions to name your key and optionally create a passphrase. This
will generate a private key (default ~/.ssh/id_rsa) and a public key (default ~/.ssh/id_rsa.pub).

Copy the public key to the Ubuntu server: You can copy the public key using the ssh-copy-id
tool from your local machine. Be sure to replace user with your actual username on the
Ubuntu server and server_ip with your server's IP address.

ssh-copy-id user@server_ip

If you cannot use ssh-copy-id, you can manually copy the contents of your public key into the
~/.ssh/authorized_keys file on the server.

Log in to your Ubuntu server and modify the SSH configuration:

sudo nano /etc/ssh/sshd_config

Change or add the following lines to disable password authentication and enable key-based
authentication:

PasswordAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication no

You can also disable root user login by adding or modifying:

PermitRootLogin no

Configuring a Ubuntu Server for a React Application using Docker and Nginx 4
Check the SSH server logs (optional).

If you're having trouble connecting, you may want to check the SSH server logs to identify
the cause of the failure. Log in to your server (with another authentication method, if
possible) and run the following command to see the latest messages from the SSH server:

sudo journalctl -u ssh

Restart the SSH Service to Apply Changes:

sudo systemctl restart ssh

Verify that you can still connect from your local machine using your private key. Once you
are able to log in and confirm this, SSH key-based authentication is correctly set up.

User Configuration
Granting Superuser (root) Privileges
To avoid logging in as root directly, create a new user with sudo privileges.

Log in as root:

ssh root@your_server_ip

Create a new user, replacing "username" with the desired username:

adduser "username"

Add the new user to the sudo group to grant administrative rights:

usermod -aG sudo "username"

To test the sudo privileges of the new user, do the following:

Configuring a Ubuntu Server for a React Application using Docker and Nginx 5
# Switch to the new user to log in
su - "username"

# Try to execute a command that requires sudo privileges, for example


sudo echo "Sudo is working."

If you encounter any error messages or permission problems, it means that the sudo privileges
have not been correctly configured for this user. In that case, you'll need to revisit the
previous steps to make sure the user has been properly added to the sudo group.

To log in as the new user with ssh, use the following command:

ssh "username"@your_server_ip

Creating a webmasters Group:

To manage web content, you can create a group called webmasters and then allocate the
appropriate permissions to directories that the group should manage.

Create the webmasters group:

bash
sudo groupadd webmasters

Assign the User to the webmasters Group:

Add your new user to the webmasters group so they can manage web server files:

bash
sudo usermod -aG webmasters "username"

Setting the Right Privileges:

Adjust the directory privileges to allow the webmasters group to read, write, and execute files
as necessary. This is typically done using chown and chmod commands on the web server
document root (e.g., /var/www/html ):

bash
# Change the ownership of the web directory
sudo chown -R "username":webmasters /var/www/html

Configuring a Ubuntu Server for a React Application using Docker and Nginx 6
# Set the correct permissions for the group
sudo chmod -R 775 /var/www/html

This will set the owner of the files to your new user, and the group ownership to the newly
created webmasters group, ensuring that both the user and other members of the group can
modify the web server's files as needed.

Ensure Proper Security Permissions:

Security is crucial, especially when managing a web server. The 775 permission set literally
translates to full read, write, and execute permissions for the user and group, and read and
execute permissions for others. It's often suitable for a web directory. However, depending on
your specific security requirements, you might need to make the permissions more restrictive.

For files that should only be readable and writable by the user and the group, use:

bash
sudo chmod -R 664 /var/www/html

For directories that should only be accessible (read and executed) by the user and the group,
use:

bash
sudo find /var/www/html -type d -exec chmod 775 {} \;

After this, the web server directories will be owned by the "username" with group
"webmasters", and they will have appropriate permissions set for web content management.

Additional Note on Web Server Setup:


Do note that the above steps just modify file system permissions and do not address web
server-specific configuration. Depending on whether you're using Apache, Nginx, or another
web server, you would need to do additional configurations such as setting up virtual hosts,
configuring server blocks, enabling site configurations, etc. Also, be sure to configure your
web server to serve the appropriate web directories ( /var/www/html is the typical default for
Apache and often used in Nginx as well).

Conclusion:
You have now successfully created a new user with sudo privileges, set up
the webmasters group, assigned the appropriate group to your user, and set the necessary file
permissions for managing web content. This basic organizational structure enhances the

Configuring a Ubuntu Server for a React Application using Docker and Nginx 7
security and manageability of your server environment, laying a solid foundation for
deploying applications, like a React app, on your DigitalOcean droplet.

Installing Packages and Preparing the System


Now that your server is secured and a user with sudo privileges is configured, the next step is
to install essential packages and tools to facilitate server setup and monitoring.

Installing Essential Utilities


Curl is a versatile tool used for downloading files from the Internet:

sudo apt install curl

Htop is an interactive process viewer for Unix systems, offering a more convenient interface
for monitoring system resources:

sudo apt install htop

Install additional network tools to support legacy commands and network troubleshooting.
Net-tools provides essential networking utilities, including ifconfig . Install it if commands
like ifconfig are not found by default:

sudo apt install net-tools

Version Management with Git


Set up Git, a distributed version control system, to manage your codebase:

To install Git and verify its successful installation, follow these steps:

sudo apt install git -y

# Verify the installation


git --version

This command will display the installed version of Git, confirming that the program is
correctly set up on your system.

Setting Up Node.js Environment with NVM

Configuring a Ubuntu Server for a React Application using Docker and Nginx 8
In this section, we'll install Node Version Manager (NVM), which allows you to manage
multiple versions of Node.js on a single machine. This is particularly useful for ensuring that
development environments remain consistent with production environments.

To install NVM, retrieve the installation script from the official NVM repository. Replace the
version in the URL with the latest available version, which you can check in the official
repository: NVM GitHub.

curl -o- <https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh> | bash

Once the script has been executed, close and reopen your terminal to ensure that the changes
take effect and NVM is available in your terminal session. This step ensures that the new
paths and environment variables added by NVM are recognized by your shell configuration
files.
Verify that NVM is installed correctly by running:

nvm --version

With NVM installed, you can now install the specific version of Node.js required by your
React project. If you need Node.js version 14.18.3:

nvm install 14.18.3

After the installation, you can verify that the correct version of Node.js is installed with the
command:

# Display the list of available Node.js versions on the machine


nvm list

# Display the version of Node.js


node --version

You now have a configured Node.js environment ready for your full-stack project on your
Ubuntu server.

Installing Nginx
Nginx is a high-performance web server that can also be used as a reverse proxy, load
balancer, and HTTP cache. Installing and configuring Nginx is an important step for serving

Configuring a Ubuntu Server for a React Application using Docker and Nginx 9
the React application and FastAPI service. To install Nginx on Ubuntu, follow these steps:
Install Nginx using the APT package manager:

sudo apt install nginx

Once the installation is complete, verify that Nginx is running:

sudo systemctl status nginx

To ensure Nginx starts automatically at server boot, enable it with the following command:

sudo systemctl enable nginx

To determine your server's public IP address and verify that Nginx is correctly serving the
default welcome page, proceed as follows:
Use an external service like icanhazip.com to find your server’s public IP address:

curl -4 icanhazip.com

The command above will display your server's public IP address. Open a web browser and
enter your server's public IP address. You should see the default Nginx welcome page,
confirming that Nginx is installed and serving content correctly.

Alternatively, if your DNS is properly configured to resolve your domain to your server's IP
address, you can also navigate to http://your_server_ip from any web browser. This should
display Nginx's default landing page. Replace "your_server_ip" with your server's actual IP
address.

Firewall Configuration
Use UFW (Uncomplicated Firewall) to establish a basic firewall configuration that allows only
essential ports (SSH, HTTP, HTTPS).

# Install UFW
sudo apt install ufw

# List available applications

Configuring a Ubuntu Server for a React Application using Docker and Nginx 10
ufw app list

# Set default rules


sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'

# Enable UFW, which will start enforcing the rules you have set
sudo ufw enable

# Check the current status of UFW in detail, including default policies and rules for each port
sudo ufw status verbose

Remember: After any significant modification to the firewall configuration, it is a good


practice to verify its status to ensure the rules are applied correctly.

Installation and Configuration of Docker Engine


Docker is an open platform for developing, deploying, and running applications. Docker
enables you to separate your applications from your infrastructure so you can deliver software
quickly. Here’s how to install Docker on your Ubuntu server:

1. Remove Old Versions:


Before installing Docker Engine, it's essential to uninstall any older versions or
conflicting versions. Run the following command to remove such packages:

for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc;


do sudo apt-get remove $pkg; done

This command removes all Docker versions that might be installed from Ubuntu's
standard package repositories or installed via manual methods.

2. Install Required Packages and Set Up Docker Repository:

Make sure to have ca-certificates installed and then configure the Docker repository:

sudo apt install ca-certificates


sudo install -m 0755 -d /etc/apt/keyrings

3. Import Docker's Official GPG Key:


This is necessary for the APT package management system to verify the authenticity of
Docker packages:

Configuring a Ubuntu Server for a React Application using Docker and Nginx 11
sudo curl -fsSL <https://download.docker.com/linux/ubuntu/gpg> -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

4. Add Docker APT Repository:


Add the Docker repository to your APT sources list:

echo \\
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] <https://downlo
ad.docker.com/linux/ubuntu> \\
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \\
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update

5. Install Docker Engine:


Install the latest version of Docker Engine, Docker CLI, and containerd using the
following command:

sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugi


n docker-compose

After running these commands, Docker should be installed, the Docker daemon should
start, and the process should be configured to start at system launch. Verify Docker is
running with:

sudo systemctl status docker

6. Verify Docker Installation:

Check the installed version of Docker to confirm it is ready to use:

docker --version

7. Enable Docker at Boot:


To configure Docker to start on boot, use the systemctl command:

sudo systemctl enable docker

Configuring a Ubuntu Server for a React Application using Docker and Nginx 12
Using Docker
With Docker operational, you can begin using it to manage containers, images, and volumes.
A few basic Docker commands include:

List Downloaded Images:

docker images -a

List Active and Inactive Containers:

docker ps -a

List Volumes:

docker volume ls

System Preparation Summary


Having completed these steps, your system is equipped with the foundational tools necessary
for subsequent server configuration tasks. The server is now ready for the deployment of the
software stack required for your React application, FastAPI backend, PostgreSQL database,
Nginx web server, and Docker containerization.
System Preparedness Summary:

System Update and Firewall Configuration: System packages have been updated, and
the firewall has been configured to permit only essential ports.

User Configuration: A user with sudo privileges has been created for secure server
management.

Essential Utilities: Tools like curl , htop , and potentially net-tools have been
installed to facilitate routine operations and network diagnostics.

Git: The distributed version control system has been set up to manage your code
repositories.

Node.js Environment with NVM: Node Version Manager (NVM) has been installed for
managing different Node.js versions, with the specific version required for the React
project.

Configuring a Ubuntu Server for a React Application using Docker and Nginx 13
Nginx: The web server and reverse proxy have been installed, configured to start on
system boot, and tested to confirm it is serving the default welcome page.

Docker: The containerization platform has been installed and configured to run
applications in isolated containers.

With these components in place, you have a solid foundation for deploying your full-stack
application. The next steps include deploying your PostgreSQL database, configuring Nginx
to serve the React application and proxy the FastAPI backend, and containerizing the
application using Docker for reliable and manageable deployment.

Deploying getechoxen.com with Nginx and


Certbot
To deploy the website getechoxen.com using Nginx and Certbot, with options for serving the
React app from either a Docker container or directly from the file system, follow the steps
below:

Prepare the Environment


Ensure your server is up-to-date and has Nginx, Certbot, and Docker installed.

sudo apt install certbot

Ensure the Nginx service is running:

sudo systemctl status nginx

Obtain SSL Certificates with Certbot


Use Certbot to obtain SSL certificates for getechoxen.com and its www subdomain:

sudo certbot --nginx -d getechoxen.com -d www.getechoxen.com

Follow the prompts to complete the SSL certificate setup, which will automatically modify
your Nginx configuration to support HTTPS.

Configure Nginx

Configuring a Ubuntu Server for a React Application using Docker and Nginx 14
Create or modify the Nginx configuration file for getechoxen.com . You already have a
configuration, so ensure it aligns with your application setup.

sudo nano /etc/nginx/sites-available/getechoxen

Here's an example configuration reflecting both deployment options:

server {
server_name getechoxen.com www.getechoxen.com;

# React app from build folder


root /var/www/react-echoxen;
index index.html;

location / {
try_files $uri $uri/ /index.html;
}

# Video CDN
location /cdn/videos/ {
alias /var/www/videos/;
autoindex on;
}

listen 443 ssl; # managed by Certbot


ssl_certificate /etc/letsencrypt/live/getechoxen.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/getechoxen.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
if ($host = www.getechoxen.com) {
return 301 https://$host$request_uri;
} # managed by Certbot

if ($host = getechoxen.com) {
return 301 https://$host$request_uri;
} # managed by Certbot

listen 80;
server_name getechoxen.com www.getechoxen.com;
return 404; # managed by Certbot
}

Docker Deployment Method


To deploy using Docker, you'll use your docker-compose setup:
Navigate to the Docker project directory:

cd /path/to/docker/project

Configuring a Ubuntu Server for a React Application using Docker and Nginx 15
Build and run the production container:

docker-compose up --build --detach react-app-prod

When deploying the React app using Docker, you'll want to configure Nginx as a reverse
proxy to your Docker container instead of directly serving files from the filesystem. Below is
the updated Nginx configuration to achieve that:

server {
server_name getechoxen.com www.getechoxen.com;

# Reverse proxy to the Docker container running the React app


location / {
proxy_pass http://localhost:8081;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

# Video CDN
location /cdn/videos/ {
alias /var/www/videos/;
autoindex on;
}

listen 443 ssl; # managed by Certbot


ssl_certificate /etc/letsencrypt/live/getechoxen.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/getechoxen.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
if ($host = www.getechoxen.com) {
return 301 https://$host$request_uri;
} # managed by Certbot

if ($host = getechoxen.com) {
return 301 https://$host$request_uri;
} # managed by Certbot

listen 80;
server_name getechoxen.com www.getechoxen.com;
return 404; # managed by Certbot
}

In this configuration:
The proxy_pass directive forwards any requests to http://localhost:8081 , which is the port
your Docker container listens on. Ensure your docker-compose.yml correctly maps the
container's port 80 to the host's port 8081 .

Configuring a Ubuntu Server for a React Application using Docker and Nginx 16
This configuration keeps the existing setup for your video CDN and SSL handling managed
by Certbot.

Direct Deployment Method


If you choose to deploy directly from the file system:
Build your React app locally:

npm run build

Copy the build folder to /var/www/react-echoxen :

sudo cp -r build/* /var/www/react-echoxen/

Ensure Nginx has the permission to read from this directory:

sudo chown -R www-data:www-data /var/www/react-echoxen

Test and Reload Nginx


After modifying the Nginx configuration and choosing a deployment method, test the Nginx
configuration for syntax errors:

sudo nginx -t

If the configuration test is successful, reload Nginx:

sudo systemctl reload nginx

Verify Deployment
Visit https://getechoxen.com/ in a web browser to ensure the site is served over HTTPS.
Check links to ensure the CDN is functioning by navigating to
https://getechoxen.com/cdn/videos/ .

Automate Certificate Renewal

Configuring a Ubuntu Server for a React Application using Docker and Nginx 17
Certbot's installation typically includes a cron job or systemd timer for automatic renewal.
Verify or test automatic renewal with:

sudo certbot renew --dry-run

This completes the setup for deploying your React app to getechoxen.com with options for
Docker-based or file-based deployment using Nginx and Certbot. Make sure to adapt file
paths and Docker configurations to your specific project structure.

Conclusion
In this guide, we've detailed how to deploy your website, getechoxen.com , using Nginx,
Certbot for SSL/TLS, and Docker to manage your React application. By setting up a flexible
deployment strategy, you can serve your application either through a Docker container or
directly from the file system, thus allowing for optimal adaptability depending on your
development and production needs.

Key Takeaways
Security and Scalability: Implementing HTTPS using Certbot ensures that your website
is secure and trustworthy for users. This step is crucial in protecting user data and
enhancing SEO.

Flexible Application Deployment: By leveraging Docker, you can isolate your


application environment, making it straightforward to manage dependencies and
versions. Docker provides a consistent development and production environment,
reducing the "it works on my machine" syndrome.

Efficient Content Delivery: Integrating a CDN within your Nginx configuration


optimizes video delivery and content distribution, ensuring faster load times for users
across different locations.

Robust Server Management: Utilizing tools like Nginx for reverse proxying ensures
your server can handle multiple tasks, like directing traffic to various services and
serving static files, all while maintaining efficiency and performance.

With these configurations and tools in place, getechoxen.com is well-prepared to handle web
traffic efficiently and securely. By following this setup, you can ensure smooth site
deployments and efficient server operations, making future expansions or adjustments
straightforward.

Configuring a Ubuntu Server for a React Application using Docker and Nginx 18
Configuring a Ubuntu Server for a React Application using Docker and Nginx 19

You might also like