我尝试在Docker上轻松将React应用程序部署到nginx上
目标
我將使用React的create-react-app創建的應用程序部署在nginx上,這是一個簡單的過程,我將其記錄下來。
创建React应用程序
我们可以使用 create-react-app 快速创建这个。
尝试使用 Docker 创建 React 环境,在 Docker 上应该能够构建。
一旦应用创建完毕,让我们使用 yarn build 将文件输出到 nginx 以供承载。
nginx的Dockerfile
以下是nginx的Dockerfile。它将复制由yarn build命令生成的文件和nginx的配置文件。
FROM nginx:1.17
COPY ./app/build /opt/app/
COPY ./nginx.conf /etc/nginx/nginx.conf
CMD ["nginx", "-g", "daemon off;", "-c", "/etc/nginx/nginx.conf"]
nginx的配置文件
让我们将location设置为放置已建立文件的位置。
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 75;
server {
listen 80;
charset utf-8;
location /{
root /opt/app/;
index index.html;
}
}
}
概括
只需要执行构建nginx的Dockerfile并启动容器,就完成了。