Configure Nginx to Serve Docker Container Locally – Nginx, Ubuntu, Gateway, Containers

containersgatewaynginxUbuntu

Hi this may be a noob question.

I am trying to replicate a 502 bad gateway error when using nginx as a web server. I have locally running VM of Ubuntu 20.04.6 LTS on which I have freshly installed nginx using

sudo apt-get install nginx

then

nginx -v which returned

nginx version: nginx/1.18.0 (Ubuntu)

and verified that it is running by the command

systemctl status nginx that shows that it is running.

Then I created a docker container with a simple Dockerfile:

# Use the official Node.js image with Alpine Linux as the base image
FROM node:14-alpine

# Set the working directory in the container
WORKDIR /usr/src/app

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

# Install dependencies
RUN npm install

# Copy the rest of the application code to the working directory
COPY . .

# Expose the port that the app will run on
EXPOSE 9000

# Define the command to run your application
CMD ["node", "app.js"]

And this is the app.js file

// app.js
const express = require('express');
const app = express();
const port = 9000;

app.get('/', (req, res) => {
  res.send('<h1>Hello, Docker World!</h1>');
});

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`);
});

When I access the localhost:9000 it returns the web page saying 'Hello, Docker World!'

Next I want to serve this localhost:9000 using the nginx web server. Then I will shutdown the docker container in an attempt to generate bad gateway error response from nginx web server.

Best Answer

Firstly, open the configuration file located at /etc/nginx/sites-enabled/default.

Check the file's content; you will easily find a location /. Add these three proxy lines inside the location /.

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://localhost:9000;
}

Then, restart the Nginx service, and you will be good to go.

systemctl restart nginx

Check out the tutorial for a case study on Nginx reverse proxy: How to Set Up Nginx Reverse Proxy Servers by Example"

Related Topic