Home > OS >  Configure Nginx to serve Static files of Angular and also reverse proxy for express
Configure Nginx to serve Static files of Angular and also reverse proxy for express

Time:01-26

i'm very new to Nginx and want to use it for serving static angular files and also proxy to a backend express server. I'm also dockerizing the frontend (with nginx) and the backend.

In the frontend i only have a button thats making a request and getting some data from express. Everytime i try this, im getting a bad gateway error.

Something is wrong but i dont have the experience to firure it out, please help.

here is a link to the Simple Projekt setup: https://github.com/stabkara/nginx-app

Front End

dockerfile

# Stage 1: Compile and Build angular codebase

# Use official node image as the base image
FROM node:latest as build

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

# Add the source code to app
COPY ./ /usr/src/app/

# Install all the dependencies
RUN npm install

# Generate the build of the application
RUN npm run build


# Stage 2: Serve app with nginx server

# Use official nginx image as the base image
FROM nginx:latest

# Copy the build output to replace the default nginx contents.
COPY --from=build /usr/src/app/dist/nginx-app /usr/share/nginx/html
COPY /nginx.conf  /etc/nginx/conf.d/default.conf

# Expose port 80
EXPOSE 80

nginx.conf

server {
  listen 80;
  sendfile on;
  default_type application/octet-stream;

  gzip on;
  gzip_http_version 1.1;
  gzip_disable      "MSIE [1-6]\.";
  gzip_min_length   256;
  gzip_vary         on;
  gzip_proxied      expired no-cache no-store private auth;
  gzip_types        text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml rss text/javascript;
  gzip_comp_level   9;

  location / {
    root /usr/share/nginx/html;
    try_files $uri $uri/ /index.html =404;
  }

  location /api {
    
    proxy_http_version 1.1;
    proxy_cache_bypass $http_upgrade;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    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://localhost:3000/api;
  }

}

request executed after clicking the button

test() {
    this.http.get(environment.apiUrl   '/array').subscribe((data) => console.log(data))
  }

environment.prod.ts (guess here is the mistake maybe)

export const environment = {
  production: true,
  apiUrl: '/api'
};

Backend

dockerfile

FROM node:16

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5 )
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 3000
CMD [ "node", "index.js" ]

index.js

const express = require("express");
const app = express();
var cors = require("cors");
const router = express.Router();
const routes = require("./routes")(router, {});
app.use("/api", routes);

app.use(cors());

// Setting the server to listen at port 3000
app.listen(3000, function (req, res) {
  console.log("Server is running at port 3000");
});

routes

module.exports = (app) => {
  app.get("/", function (req, res) {
    res.json({
      number: 1,
    });
  });

  // Defining get request at '/multiple' route
  app.get("/multiple", function (req, res) {
    res.json({
      number: 1,
      name: "John",
      gender: "male",
    });
  });

  // Defining get request at '/array' route
  app.get("/array", function (req, res) {
    res.json([
      {
        number: 1,
        name: "John",
        gender: "male",
      },
      {
        number: 2,
        name: "Ashley",
        gender: "female",
      },
    ]);
  });

  return app;
};

I hope you can help me. It would be awesome! Thanks in advance! (Serving static files is working, but the proxy not)

CodePudding user response:

In a container context, localhost refers to the container itself. So when you, in your nginx config, proxy_pass to http://localhost:3000/api you're sending the request to the nginx container.

You want to send it to the backend container. If you're using the docker-compose file in the repo you've linked, then you can use the service names of the containers as their hostnames. So if you change the proxy_pass to

proxy_pass http://backend:3000/api;

it should pass the requests on to the backend container.

I made a very minimal example of doing what you're trying to do a while back. Feel free to take a look if you still have trouble getting it to work. https://github.com/kodedylf/docker-node-nginx

  •  Tags:  
  • Related