Creating Docker Image and then transferring to a server.
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 image2FROM node:18-alpine AS base34# Enable Corepack to manage package managers like pnpm5RUN corepack enable67# Set the working directory8WORKDIR /app910# Copy package.json and pnpm-lock.yaml11COPY package.json pnpm-lock.yaml ./1213# Install dependencies (only production dependencies if applicable)14RUN pnpm install --frozen-lockfile --prod1516# Copy the rest of the app code including the build artifacts17COPY . .1819# Expose the app port20EXPOSE 30002122# Start the app23CMD ["pnpm", "start"]24
.dockerignore
1node_modules2.git3.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 build2docker 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_web34# Remove the container5docker rm payload_web67# Pull the latest image8docker pull your_docker_name/payload_web-app:latest910# Remove unused images11docker image prune -f1213# run docker having it restart unless stopped14docker 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:latest1819# attach docker to terminal *optional*20docker attach payload_web