1 搭建Docker容器

关于docker容器的搭建,我们采用dockfile文件搭建nginx应用容器。

dockerfile文件的编写

# 使用官方Nginx镜像作为基础
FROM nginx:latest
# 将本地自定义配置文件复制到容器中
COPY nginx.conf /etc/nginx/conf.d
# 将网站文件复制到容器中的默认目录
COPY ./html /usr/share/nginx/html
# 暴露80端口
EXPOSE 80
# 启动Nginx服务
CMD ["nginx", "-g", "daemon off;"]

准备Nginx配置文件

创建一个名为nginx.conf的文件,内容示例:

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  1.html index.htm;
    }
    location /2.html {  
        root   /usr/share/nginx/html;
        index  2.html index.htm;
    }
}

listen 80:该指令配置Nginx监听IPv4地址的80端口(HTTP默认端口);
listen [::]:80:配置Nginx监听IPv6地址的80端口,[::]表示所有可用的IPv6地址;
server_name localhost:定义服务器名称(虚拟主机标识),此处设置为localhost,表示匹配请求头中的Host为localhost的请求;
location / {:匹配所有以/开头的请求路径(即所有请求);
root /usr/share/nginx/html:指定根目录为/usr/share/nginx/html,静态文件将从该目录下查找;
index 1.html index.htm:设置默认索引文件,优先尝试返回1.html,若不存在则返回index.htm。

编写html文件

<!DOCTYPE html>
<html>
<head>
    <title>Nginx in Docker</title>
</head>
<body>
    <h1>Welcome to Nginx running in Docker!</h1>
     <a href="2.html">Jump to webpage</a><br/>
</body>
</html>

2 运行docker容器

docker build -t my-web:latest .

通过dockerfile构建镜像

docker run my-web

运行这个镜像构建容器。

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐