node.jsnginxdeploymentsveltesveltekit

How to deploy a svelte kit app after build using nginx as web server


I have a svelte kit project. I want to deploy the app in an Nginx web server after an npm run build. At the moment I have a node container and I use to start using npm run preview. It's working fine, but I want to deploy in a production environment using build.

How could I do that?

ref: https://kit.svelte.dev/docs#command-line-interface-svelte-kit-build


Solution

  • As @Caleb Irwin said, you can run node ./build/index.js

    The NGINX configuration will look like this:

    upstream sveltekit {
      server 127.0.0.1:3000;
      keepalive 8;
    }
    
    
    server {
      # listen ... 
      # servername ...
    
      # root ... (folder with an index.html in case of sveltekit being crashed)
    
      location / {
        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_set_header X-Forwarded-Proto $scheme;
    
        proxy_pass http://sveltekit;
        proxy_redirect off;
    
        error_page 502 = @static;
      }
    
      location @static {
        try_files $uri /index.html =502;
      }
    }
    

    (I'm not a NGINX pro and welcomes feedback to improve on it)

    You may also want to make the SvelteKit app listen only to localhost by adding the environment HOST=127.0.0.1 before running node build/index.js. This will prevent the port 3000 from being reached from the outside.

    You can also look into using pm2 to manage the sveltekit process, including running it on each of your cores in cluster mode, automatic restart in case of server crash / reboot.