使用 Docker 部署 Astro

使用指令建立 astro 的 node 設定檔:
    
npm run astro add node
    

就一路 y 下去即可,輸出結果如下:
    
npm run astro add node
> astro add node

✔ Resolving packages...

  Astro will run the following command:
  If you skip this step, you can always run it yourself later

 ╭───────────────────────────────────╮
 │ npm install @astrojs/node@^8.2.5  │
 ╰───────────────────────────────────╯

√ Continue? ... yes
✔ Installing dependencies...

  Astro will make the following changes to your config file:

 ╭ astro.config.mjs ─────────────────────────────╮
 │ import { defineConfig } from 'astro/config';  │
 │                                               │
 │ import node from "@astrojs/node";             │
 │                                               │
 │ // https://astro.build/config                 │
 │ export default defineConfig({                 │
 │   output: "server",                           │
 │   adapter: node({                             │
 │     mode: "standalone"                        │
 │   })                                          │
 │ });                                           │
 ╰───────────────────────────────────────────────╯

  For complete deployment options, visit
  https://docs.astro.build/en/guides/deploy/

√ Continue? ... yes

   success  Added the following integration to your project:
  - @astrojs/node
    

在專案根目錄建立 Dockerfile
(此 Dockerfile 會對外開放 4321 port,可以由此連入,在建立 docker 容器時可以映射成其他 port)
    
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
    

建立 .dockerignore ,避免某些檔案被我們複製進 Docker:
    
FROM node:lts AS runtime
.DS_Store
node_modules
dist
    

建立 docker image:
(my-astro-image 是筆者自訂的 docker image 名稱) (指令最後面有一個點)
    
docker build -t my-astro-image . 
    

使用 docker image 建立 docker 容器:
(my-astro-container 是筆者的 docker 容器名稱,my-astro-image 是剛剛建立的 docker image 名稱, 80 是本機可以存取的 port,4321 是 docker 容器對外開放的 port)
    
docker run -p 80:4321 -d --name my-astro-container my-astro-image 
    

依照上面的步驟做完後就可以使用下面的網址瀏覽到自己的在 Docker 容器中的 Astro 網頁了!
    
    http://localhost:80/
    



參考資料:
Astro.Docs - Build your Astro Site with Docker

留言