How to build and run a Node.js application using Nginx, Docker and Redis
Thanks to Node.js - Millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language. Node.js is a free, open-sourced, cross-platform JavaScript run-time environment. It is capable to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.
In this quickstart guide, you will see how to build a Node.js application (visitor counter) using Nginx, Redis and Docker.
#
What do you need?- Node.js: An open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.
- Nginx: An open source software for web serving, reverse proxying, caching, load balancing, media streaming, and more.
- Docker: a containerization platform for developing, shipping, and running applications.
- Docker Compose: A tool for defining and running multi-container Docker applications.
#
Project structure#
Prerequisite:โ Install Docker Desktop
Visit https://docs.docker.com/desktop/mac/install/ to setup Docker Desktop for Mac or Windows on your local system.
info
Docker Desktop comes with Docker compose installed by default, hence you don't need to install it separately.
#
Step 1. Create a Docker compose fileCreate an empty file with the below content and save it by name - "docker-compose.yml"
The compose file defines an application with four services redis
, web1
, web2
and nginx
.
When deploying the application, docker-compose maps port 80 of the web service container to port 80 of the host as specified in the file.
info
By default, Redis runs on port 6379. Make sure you don't run another instance of Redis on your system or port 6379 on the host is not being used by another container, otherwise the port should be changed.
#
Step 2. Create an nginx directory and add the below files:#
File: nginx/nginx.conf#
File: Dockerfile#
Step 3. Create a web directory and add the below files:#
File: web/Dockerfile#
File: web/package.json#
File: web/server.js#
Step 4. Creating a web1 directory and add the below files:#
File: Dockerfile#
File: server.js#
File: package.json#
Step 5. Deploy the applicationLet us deploy the full-fledged app using docker-compose
#
Expected resultListing containers must show three containers running and the port mapping as below:
#
Step 6. Testing the appAfter the application starts, navigate to http://localhost:80
in your web browser or run:
#
Step 7. Monitoring Redis keysIf you want to monitor the Redis keys, you can use monitor command. Install redis-client in your Mac system using brew install redis
and then directly connect to Redis container by issuing the below command: