Search code examples
node.jsdockergithubdockerfilegithub-actions

How to solve Error: Cannot find module in Custom DockerFile based GitHub Actions


I have been trying to setup a GitHub Action that runs a single node script (called index.js). When GitHub Actions then runs the container after building it, it automatically sets the working directory to /github/workspace, which is why I have replicated this in my Dockerfile ( WORKDIR /github/workspace/ ).

node:internal/modules/cjs/loader:1147
  throw err;
  ^

Error: Cannot find module '/github/workspace/index.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
    at Module._load (node:internal/modules/cjs/loader:9[8](https://github.com/Sonichigo/GitHub-Action-s/actions/runs/7500548232/job/20419453468#step:3:9)5:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
    at node:internal/main/run_main_module:28:4[9](https://github.com/Sonichigo/GitHub-Action-s/actions/runs/7500548232/job/20419453468#step:3:10) {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

Node.js v20.[11](https://github.com/Sonichigo/GitHub-Action-s/actions/runs/7500548232/job/20419453468#step:3:12).0

This suggests that the file does not exist. The debug output I added when building the container shows me otherwise though (root directory shortened for legibility)

I tried copying the index.js file to /github/workspace/index.js in the container, it will be in the correct location when the GitHub Action runs, but it still doesn't work! Instead I get different error! This is my docker file:-

FROM node:lts

COPY package*.json ./

RUN npm install

COPY index.js /github/workspace/index.js
RUN ["chmod", "+x", "/github/workspace/index.js"]

RUN ls
ENTRYPOINT ["node", "/github/workspace/index.js"]

This fix throws Error: Resource not accessible by integration


Solution

  • The above error message was due to the contents for Dockerfile as well as the permission scope of GitHub actions.

    select settings -> Actions -> Workflow permissions -> Read and write permissions .

    updated dockerfile:-

    FROM node:22-alpine
    
    WORKDIR /app
    
    COPY package*.json /app/
    
    RUN cd /app/ && npm install -y
    
    COPY . /app/
    
    RUN ls
    
    RUN chmod +x /app/entrypoint.sh
    
    ENTRYPOINT ["/app/entrypoint.sh", "/app/index.js"]
    

    based on above i updated the entrypoint.sh as well:-

    #!/bin/sh -l
    
    echo "Running action"
    
    ## verfiying the path
    echo "$PWD" 
    
    ## cd is necessary to move to the workdir otherwise we will get error module not found
    cd /app && node index.js