大网数据广告活动
服务器运维问答

Configure nginx running locally to server the port running docker container locally

· 52CE 我爱测

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…

问题原文

原帖链接 · Curious Developer · CC BY-SA 4.0

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.

已采纳解答

原帖链接 · Shivam Ahuja · CC BY-SA 4.0

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"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2023-11-16)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。