Astro JS - Build With Docker



What is Docker?

Docker is a platform used to develop, ship, and run applications inside containers. Containers are lightweight, and portable environments that can run on any machine that has Docker installed. Docker images and containers can be easily deployed to many different platforms, like AWS, Azure, and Google Cloud.

Prerequisites

Before you start using Docker with Astro, make sure you have the following prerequisites:

  • Docker installed on your machine
  • Basic knowledge of Docker and containers
  • Basic knowledge of Astro JS

Install Docker

To use Docker with Astro, you need to install Docker on your machine. You can download Docker from the official website. Once you have installed Docker, you can verify the installation by running the following command:

>> docker --version

This will display the version of Docker installed on your machine. If you see the version number, it means Docker is installed correctly.

Create a Dockerfile in Astro

Dockerfile is a text file that contains all the commands to assemble an image. This file contains the instructions to build your site, which will differ depending on your needs. You can create a Dockerfile in the root directory of your Astro project. Here is an example of a Dockerfile for an Astro project.

SSR Dockerfile

The SSR dockerfile is used for server side rendering. This Dockerfile will build your site and serve it using Node.js on port 4321 and therefore requires the Node adapter installed in your Astro project.

# Dockerfile

FROM node:lts AS runtime
WORKDIR /app

COPY . .

RUN npm install
RUN npm run build

ENV HOST=0.0.0.0
ENV PORT=4321
EXPOSE 4321
CMD node ./dist/server/entry.mjs

The .dockerignore file

The .dockerignore file is used to specify files and directories that should be ignored in the Docker COPY or ADD commands. This is similar to the .gitignore file. You can create a .dockerignore file in the root directory of your Astro project. Here is an example of a .dockerignore file:

// File - .dockerignore

.DS_Store
node_modules
dist

Multi Stage Build

Multi stage build is a technique used to reduce the size of the final Docker image. It optimizes the build process for your site by not reinstalling the npm dependencies when only the source code changes. This can reduce the build time even by minutes, depending on the size of your dependencies. The dockerfile below define multi stage build process.

FROM node:lts AS base
WORKDIR /app

COPY package.json package-lock.json ./

FROM base AS prod-deps
RUN npm install --omit=dev

FROM base AS build-deps
RUN npm install

FROM build-deps AS build
COPY . .
RUN npm run build

FROM base AS runtime
COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist

ENV HOST=0.0.0.0
ENV PORT=4321
EXPOSE 4321
CMD node ./dist/server/entry.mjs
Advertisements