Search code examples
dockerdockerfilegithub-actions

Docker COPY failed on gitignored file on Github Action


I am as novice as it comes to Docker and have just been through stuff at the wall until it sticks. But now I'm stuck.

I have the following folder structure in my project

📦project
 ┣ 📂.github
 ┃ ┗ 📂workflows
 ┃ ┃ ┗ 📜deploy.yml
 ┣ 📂server
 ┃ ┣ 📜Dockerfile
 ┗ 📂web

My Dockerfile in ./server is as follows

FROM node:16

WORKDIR /usr/src/app

COPY package.json ./
COPY yarn.lock ./

RUN yarn

COPY . .
COPY .env.production .env

RUN yarn build

ENV NODE_ENV production

EXPOSE 8080
CMD [ "node", "dist/index.js" ]
USER node

Amongst other things, I am trying to copy the contents .env.production into a new file .env. But .env.production only exists in my local directory as it exists in my .gitignore file.

So running

docker build -t <username>/<projectname>:<version> .

works fine locally, but not when I try to run it on a github action, I get the following error

COPY failed: file not found in build context or excluded by .dockerignore: stat .env.production: file does not exist

I also tried to use docker/build-push-action@v3

But I was getting a similar error

buildx failed with: error: failed to solve: failed to compute cache key: failed to calculate checksum of ref "/.env.production": not found

My deploy.yml file is as follows

name: Deploy Application

on:
  push:
    branches: ["master"]

  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: ./server

    strategy:
      matrix:
        node-version: [16.13.0]

    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Node Version ${{ matrix.node-version }}
        uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}
          cache: "yarn"
          cache-dependency-path: "./server/yarn.lock"
      - name: Publish docker image
        run: |
          docker login --username ${{ secrets.DOCKER_USER }} --password '${{ secrets.DOCKER_PASSWORD }}'
          docker build -t ${{ secrets.DOCKER_USER }}/${{ secrets.DOCKER_REPOSITORY }}:1 .

What's the best solution to get my environment values from my local .env.production file (without exposing it) and copy to an .env file?


Solution

  • I opted for using SpicyPizza/[email protected] to create the .env.production file when running the workflow and using GitHub Action secrets are the environment variables values so they do not get exposed.

    - name: Create .env.production file
      uses: SpicyPizza/[email protected]
      with:
        envkey_SESSION_SECRET: ${{ secrets.SESSION_SECRET }}
        directory: ./server/
        file_name: .env.production
        fail_on_empty: false