VPS部署Rails7+Nginx后JS/CSS无法正常加载求助
Rails 7 + Importmap + Docker/Nginx 资源加载问题排查方案
1. 确认Rails资产预编译流程
- 生产环境下必须开启资产预编译,检查
config/environments/production.rb配置:config.assets.compile = false config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=31536000' } - Dockerfile中必须加入预编译命令,确保镜像包含编译后的资产:
RUN bundle exec rails assets:precompile RAILS_ENV=production
2. Importmap 配置校验
- 检查容器内
public/assets/importmap.json是否存在,该文件由Importmap在预编译时生成,确保路径指向正确的编译后资源。 - 确认
config/importmap.rb中所有依赖的包已正确pin,生产环境不会动态拉取资源,必须提前预编译。
3. Nginx 配置修正
- 调整Nginx配置,优先处理静态资产,其余请求转发给Rails:
server { listen 443 ssl; server_name trytech.app; root /app/public; index index.html; # 静态资产直接返回,设置强缓存 location ~ ^/assets/ { expires 1y; add_header Cache-Control "public, immutable"; gzip_static on; try_files $uri =404; } # 所有非资产请求转发到Rails服务 location / { proxy_pass http://rails:3000; 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; } # 补充SSL证书相关配置 } - 注意:
http://rails:3000中的rails需与docker-compose.yml里的Rails服务名一致。
4. Docker-compose 配置优化
- 使用共享卷让Nginx访问Rails的
public目录,避免挂载本地开发目录覆盖生产资产:services: rails: build: . command: bundle exec puma -C config/puma.rb environment: - RAILS_ENV=production - RAILS_SERVE_STATIC_FILES=false # 由Nginx处理静态资源,关闭Rails的静态服务 volumes: - rails_public:/app/public nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf - rails_public:/app/public depends_on: - rails volumes: rails_public:
5. 验证与调试
- 直接访问
https://trytech.app/assets/application.css和https://trytech.app/assets/application.js:- 返回404:检查资产预编译是否执行,或Nginx/容器路径配置错误
- 返回内容但页面不加载:检查页面中资源引用路径是否为绝对路径(Rails默认生成绝对路径,确保
config.action_controller.asset_host未错误配置)
内容的提问来源于stack exchange,提问作者Italo
相关产品推荐
相关产品推荐

