Docker: How to dockenize an Astro app
Brief introduction about Astro:
Astro is a modern front-end framework for building fast, optimized web applications. It allows you to write components using your favorite JavaScript framework (or no framework at all) and then renders your page to static HTML and CSS at build time.
Create app
First, let’s create an astro app.
npm create astro@latest
The next step is configure vite to allow hot reload in docker.
Inside astro.config.mjs
add the following:
export default defineConfig({
vite: {
server: {
watch: { usePolling: true },
},
},
})
And configure the start script in package.json
adding the --host
flag, this
will allow us to access the app from outside the container.
"scripts": {
"start": "astro dev --host",
}
Dockfile
Now, let’s create a Dockerfile
to define our image.
FROM node:18-slim
WORKDIR /app
COPY package*.json .
RUN npm ci --audit=false --fund=false
CMD ["npm", "start"]
Check the version of node in the docker hub.
Docker compose
To make our life easier, let’s create a docker-compose.yml
file.
services:
web:
build: .
ports:
- "4321:4321"
volumes:
- "./:/app"
- "/app/.tscache"
- "/app/dist"
- "/app/node_modules"
container_name: carlosnc
Docker ignore
To avoid copying unnecessary files to the container, let’s create a .dockerignore
file.
node_modules
npm-debug.log
Running:
For the first time, we need to build the image. The following command will build the image and start the container.
docker-compose up --build
To start the container without rebuilding the image, run:
docker-compose up
To clean up the container, run:
docker compose rm --stop --volumes --force
If everything is ok, you will see the log like this:
=> [web internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 161B 0.0s
=> [web internal] load .dockerignore 0.0s
=> => transferring context: 67B 0.0s
=> [web internal] load metadata for docker.io/library/node:18-slim 1.1s
=> [web 1/4] FROM docker.io/library/node:18-slim@sha256:fe687021c06383a2bc5eafa6db29b627ed28a55f6bdfbcea108f0c624b783c37 0.0s
=> [web internal] load build context 0.0s
=> => transferring context: 72B 0.0s
=> CACHED [web 2/4] WORKDIR /app 0.0s
=> CACHED [web 3/4] COPY package*.json . 0.0s
=> CACHED [web 4/4] RUN npm ci --audit=false --fund=false 0.0s
=> [web] exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:a3a75285e2fd150e70ff62ac91b7486c536d8f00184877d2dd64f8f1fe39c854 0.0s
=> => naming to docker.io/library/carlosnc-web 0.0s
[+] Running 1/0
✔ Container carlosnc Created 0.0s
Attaching to carlosnc
carlosnc |
carlosnc | > carlosnc@0.0.1 start
carlosnc | > astro dev --host
carlosnc |
carlosnc |
carlosnc | 🚀 astro v3.6.4 started in 561ms
carlosnc |
carlosnc | ┃ Local http://localhost:4321/
carlosnc | ┃ Network http://172.19.0.2:4321/
carlosnc |
carlosnc | 02:43:02 PM [astro] reload /src/pages/notes/docker-dockenize-astro.mdx