我在配置 Nginx 基础镜像(任何版本)时遇到问题,
-第一阶段的应用程序需要复制到 HTTP 服务器并设置为默认启动并显示为默认(开始)页面
- 包括操作正确性检查(HEALTHCHECK)
我的 Dockerfile:
# Stage 1: Build Stage
FROM node:alpine AS builder
# Install build dependencies
RUN apk add --update curl && \
rm -rf /var/cache/apk/*
WORKDIR /usr/app
# Copy package.json and install dependencies
COPY ./package.json ./
RUN npm install
# Copy application code
COPY ./index.js ./
# Stage 2: Runtime Stage
FROM nginx:latest
# Remove default nginx website
RUN rm -rf /usr/share/nginx/html/*
# Copy built files from the builder stage
COPY --from=builder /usr/app /usr/share/nginx/html
# Set working directory
WORKDIR /usr/share/nginx/html
# Expose port
EXPOSE 80
# Define version argument
ARG VERSION
ENV VERSION=production.${VERSION:-v1.0}
# Health check configuration
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:80/ || exit 1
# Command to run the application
CMD ["nginx", "-g", "daemon off;"]
我的 nginx.conf:
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
# Health check
location /healthcheck {
access_log off;
return 200 'OK';
}
}
其余代码:
const express = require('express');
const os = require('os');
const app = express();
const port = 8084;
app.get('/', (req, res) => {
let response = `Adres IP serwera: ${getIPAddress()}\n`;
response += `Nazwa serwera (hostname): ${os.hostname()}\n`;
response += `Wersja aplikacji: ${process.env.VERSION}\n`;
res.send(response);
});
app.listen(port, () => {
console.log(`Aplikacja jest dostępna na porcie ${port}`);
});
function getIPAddress() {
const interfaces = os.networkInterfaces();
for (const dev in interfaces) {
const iface = interfaces[dev].filter(details => details.family === 'IPv4' && !details.internal);
if (iface.length > 0) return iface[0].address;
}
return '0.0.0.0';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Web App</title>
</head>
<body>
<h1>Welcome to Simple Web App</h1>
<p>This is a simple web application.</p>
<p>Server IP Address: [SERVER_IP_ADDRESS]</p>
<p>Server Hostname: [SERVER_HOSTNAME]</p>
<p>Application Version: [APP_VERSION]</p>
</body>
</html>
我使用此命令来运行图像:
docker build --build-arg VERSION=3.0.0 -f Dockerfile10 -t local/base:v10 . -> 创建成功
docker run -d -p 8093:8080 --name web13 local/base:v10 ->(运行状况:开始)
curl http://localhost:8093 ->curl: (52) 来自服务器的空回复
docker log -> 错误消息“directory index of '/usr/share/nginx/html/' is禁止”表示Nginx正在尝试服务根目录,但找不到要显示的索引文件。 (我的目录中有index.html 和其余文件)
我认为这里的问题与文件权限有关,您应该在 docker 中更改文件夹的访问权限,检查this out