Target
We will use NGINX as a reverse proxy for the NodeJS server
2 Docker images from Docker Hub will be used:
- NodeJS
- NGINX
environment
- NodeJS
- Docker
Example
NodeJS HTTP Service
We will create a simple node server. We will use the modules in httpnode and make a simple http server. The server.js file contains the code of our server
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Node & Docker Running...");
});
server.listen(3333);
console.log("Node HTTP Server started at http://localhost:3333/");
If we run node server.js on the terminal, it will start the server on port 3333 of the local host
We can open the browser and visit http://localhost:3333/
Now, we want to create a docker image for our node server. To do this, we need to create a file named Dockerfile using the following command
FROM mhart/alpine-node
COPY server.js.
EXPOSE 3333
CMD node server.js
Here, I used mhart/alpine-node
(Minimal Node.js Docker Image) to have a NodeJS environment
EXPOSE 3333
means 3333
as the access port
Now that we have the Dockerfile
ready, we will build a Docker image from this file
docker build -t docknode.
I will now run the docker image, which will create a container for us
docker run -d -p 3333:3333 --name node-server docknode
After running this command, our NodeJS server should run node-server
in a Docker container named
Nginx anti-generation
The NodeJS server in the Node Docker image is running, next we need to add the NGINX reverse proxy
Use the official NGINX image from DockerHub
FROM nginx
COPY default.conf /etc/nginx/conf.d/
default.conf
server {
location / {
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;
proxy_pass http://server:3333;
}
}
In the configuration, we have http://server:3333
. This 3333
is the port from our NodeJS Docker
container
docker build -t docknginx.
In order to verify that our image is available on our local machine, we can run the following command to view the list of images
docker images
Run Nginx anti-generation server container
docker run -d -p 8080:80 --link node-server:server --name nginx-proxy docknginx
After running the command, if we now go to the browser and click on http://localhost:8080/
, we can see that our NodeJS application is now running on this port
We are actually accessing the NodeJS server through NGINX because it is used as a reverse proxy here
Post comment 取消回复