Skip to main content

Dockerfile Templates for Svelte Framework

This guide helps you create appropriate Dockerfiles for Svelte-based projects.

Key Points for All Dockerfiles​

  1. Using official Node.js images
  2. Creating a non-root user for enhanced security
  3. Using environment variables for greater flexibility
  4. Optimization for Svelte
FROM node:$node_version as build
ARG UID=1000
ARG GID=1000
RUN groupadd -g $GID -o app && \
useradd -g $GID -u $UID -mr -d /home/app -o -s /bin/bash app
USER app
WORKDIR /home/app
COPY --chown=app:app app/ /home/app/
RUN npm install
#CMD [ "npm", "run", "build" ] or CMD [ "npm", "run", "dev" ]
FROM nginx:$nginx_version as production
COPY --from=BUILD /home/app/build/ /usr/share/nginx/html/
RUN echo 'server {\n\
listen 3000;\n\
server_name _;\n\
location / {\n\
root /usr/share/nginx/html;\n\
try_files $uri $uri/ /index.html;\n\
}\n\
location /index.html {\n\
root /usr/share/nginx/html;\n\
expires 0d;\n\
}\n\
}' > /etc/nginx/conf.d/default.conf
info
  • This Dockerfile uses a multi-stage structure: build stage and production stage.
  • In the build stage, we compile the Svelte project.
  • In the production stage, we transfer the built files to an Nginx server.
  • Nginx configuration is set up for proper execution of the Svelte application (SPA).
  • Note that in Svelte, the output directory is build by default (instead of dist in Vue).
caution
  • Replace $node_version with your desired Node.js version.
  • Replace $nginx_version with your desired Nginx version.
  • Depending on your project needs, you can choose between npm run build and npm run dev.

Building and Running the Dockerfile​

To build the Dockerfile and create an image, use the command:

docker build -t [ProjectName] .
  • -t: Giving a specific tag and name for the project

And then to run it:

docker run -p outport:inport[3000] --name=container-name -d [ProjectName]
  • -p: Setting the port for running the project
  • outport: External port
  • inport: Internal project port that you specified in the Dockerfile
  • --name: Setting the container name
  • -d: Running the container in detached mode
caution
  1. Security: Always use the latest stable versions of Node.js and Nginx.
  2. Testing: Before deploying to production, make sure to test your Docker image in a production-like environment.
  3. Svelte Kit: If you're using Svelte Kit, you might need additional configurations in the Nginx setup.