Programming

Creating Docker Image and then transferring to a server.

Written by Preston Garrison ai
Post hero image

Creating a Docker Image

The best way to transfer your docker image to a server is to upload it to Docker Hub and then pull it from the hub. This is great because it only transfers as much data as is required for the changes to the file.

One thing to do is make sure your .env file is in your .dockerignore file, and then map to it when running docker, or running the build.

I am using this with a Payload CMS project, and here are my current configs

Dockerfile

1# Use a Node.js base image
2FROM node:18-alpine AS base
3
4# Enable Corepack to manage package managers like pnpm
5RUN corepack enable
6
7# Set the working directory
8WORKDIR /app
9
10# Copy package.json and pnpm-lock.yaml
11COPY package.json pnpm-lock.yaml ./
12
13# Install dependencies (only production dependencies if applicable)
14RUN pnpm install --frozen-lockfile --prod
15
16# Copy the rest of the app code including the build artifacts
17COPY . .
18
19# Expose the app port
20EXPOSE 3000
21
22# Start the app
23CMD ["pnpm", "start"]
24

.dockerignore

1node_modules
2.git
3.env

I like to do a manual build first, and then run the docker command. I am building a dual image file, so it works on mac as well as a normal x86 server.

1pnpm build
2docker buildx build --platform linux/amd64,linux/arm64 -t your_docker_name/payload_web-app:latest --push .

Once the file is uploaded you can then move to your server. I'll assume the image is already running, so if your not just updating it may be a little different, but these commands should work. I put my .env file in ~/payload.env, adjust the command according to where you put the file. If your running payload, its important you update this file for the server URL and the database. Also i made a directory on the local server in /var/www/media and am mounting it inside the docker, so when i update the docker i don't lose the uploaded images.

1# Stop the container (if it's running)
2docker stop payload_web
3
4# Remove the container
5docker rm payload_web
6
7# Pull the latest image
8docker pull your_docker_name/payload_web-app:latest
9
10# Remove unused images
11docker image prune -f
12
13# run docker having it restart unless stopped
14docker run -d --name payload_web \
15 --restart unless-stopped -p 3000:3000 \
16 --env-file ~/payload.env -v /var/www/media:/var/www/media \
17 your_docker_name/payload_web-app:latest
18
19# attach docker to terminal *optional*
20docker attach payload_web