How to serve static files with nginx inside of a docker container?

前端 未结 1 1703
醉话见心
醉话见心 2021-02-20 04:07

I\'m using boot2docker since I\'m running Mac OSX. I can\'t figure out how serve up static files using nginx that is running inside a docker container (that also contains the st

相关标签:
1条回答
  • 2021-02-20 04:49

    Your issue isn't related to docker but to your nginx configuration.

    In your nginx config file, you define /var/www/ as the document root (I guess to serve your static files). But below that you instruct nginx to act as a reverse proxy to your node app for all requests.

    Because of that, if you call the /index.html URL, nginx won't even bother checking the content of /var/www and will forward that query to nodejs.

    Usually you want to distinguish requests for static content from requests for dynamic content by using a URL convention. For instance, all requests starting with /static/ will be served by nginx while anything else will be forwarded to node. The nginx config file would then be:

    worker_processes auto;
    
    daemon off;
    
    events {
      worker_connections 1024;
    }
    
    http {
      server_tokens off;
      upstream node-app {
        ip_hash;
        server 192.168.59.103:5000;
      }
      server {
        listen 80;
    
        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
          expires 1d;
        }
    
        location /static/ {
          alias /var/www/;
          index index.html;
        }
    
        location / {
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
          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-NginX-Proxy true;
    
          proxy_http_version 1.1;
          proxy_pass http://node-app;
          proxy_cache_bypass $http_upgrade;
        }
    
      }
    }
    
    0 讨论(0)
提交回复
热议问题