Docker container package
Prepare Dockerfile
Dockerfile
for nextjs as example, follows this nextjs issue to fix in later version.
# Stage 1: Build the application
FROM node:18-alpine as builder
# Set the working directory
WORKDIR /app
# Set environment variables
ENV NODE_ENV production
# Copy source code
COPY ./ ./
# Install and build
RUN yarn && yarn build
# Stage 2: Create the final image
FROM node:18-alpine
# Set the working directory
WORKDIR /app
# Copy only necessary files from the builder stage
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/.next/standalone ./app
COPY --from=builder /app/public ./app/public
COPY --from=builder /app/.next/static ./app/.next/static
# Link package to github repo
ARG repo
LABEL org.opencontainers.image.source https://github.com/${repo}
# Expose port 3000
EXPOSE 3000
# set hostname to localhost
ENV HOSTNAME "0.0.0.0"
# CMD to start the application
CMD ["node", "app/server.js"]
.dockerignore
/node_modules
.env.local
.env.development.local
.env.test.local
.env.production.local
next.config.js
module.exports = {
output: 'standalone',
}
Deploy from local
Login
- Get your
${PAT}
from https://github.com/settings/tokens withwrite:packages
permission.
docker login --username ${username} --password ${PAT} ghcr.io
Build image
docker build . --build-arg repo=${username}/${reponame} -t ghcr.io/${username}/${reponame}:${version} --no-cache
Push image
docker push ghcr.io/${username}/${reponame}
Test Image
- Logout
docker logout
- Remove existed image.
> docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ghcr.io/${username}/${reponame} latest 14740a153484 9 minutes ago 511MB
> docker image rm 1474
- Run container
docker run -d -p 3000:3000 ghcr.io/${username}/${reponame}:${version}
Deploy from Github CI
Add Write Package Permission PAT To Repo Secrets
- Add your
PAT
at https://github.com/${username}/${reponame}/settings/secrets/actions and named itWRITE_PACKAGE_TOKEN
.
Github CI Yml
Add .github\workflows\container.yml
to deploy image when push a tag.
name: Publish package to GitHub Packages
on:
push:
tags:
- '*'
jobs:
publish-package:
runs-on: ubuntu-latest
permissions:
packages: write
steps:
- uses: actions/checkout@v3
- run: |
docker login --username $ --password $ ghcr.io
docker build . --build-arg repo=$ -t ghcr.io/$:$ --no-cache
docker push ghcr.io/$:$
docker tag ghcr.io/$:$ ghcr.io/$:latest
docker push ghcr.io/$:latest