Search code examples
node.jsdockerfilecreate-react-appdocker-buildreact-scripts

server.tsx module not found when building docker image


When running my create-react-app server on my local machine with npm run start, the server starts and works fine. However, when attempting to dockerize my app, I get the error:

#12 2.029 Error: Cannot find module '/usr/src/app/sms-fe/src/server.tsx'
#12 2.029     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1085:15)
#12 2.029     at Function.Module._load (internal/modules/cjs/loader.js:928:27)
#12 2.029     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
#12 2.029     at internal/main/run_main_module.js:17:47 {
#12 2.029   code: 'MODULE_NOT_FOUND',
#12 2.029   requireStack: []
#12 2.029 }
#12 2.033 npm ERR! code ELIFECYCLE
#12 2.034 npm ERR! errno 1

It seems it can't find the the server.tsx file. However, despite there being no physical src/server.tsx file on my local machine, the app still works fine. I'm guessing that react-scripts possibly is doing something in the background but I'm not sure what.

Any ideas?

Here are my Docker and package.json files.

Dockerfile

FROM node:14.7-alpine

WORKDIR /usr/src/app/sms-fe

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install -g typescript

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

COPY . ./

EXPOSE 8080 

# RUN node scripts/start.js && node ./src/server.tsx
RUN ["npm", "run", "start"]

package.json

"scripts": {
    "start": "react-scripts start && node ./src/server.tsx",
...

Solution

  • This turned out to be a problem with running my COPY command after npm install. To cause further issues. It also seems the first of two copy commands (COPY package*.json ./) didn't copy my package-lock.json file or it was overidden, possibly by the second COPY command.

    This was discovered by:

    1. Removing the npm run start command.
    2. Running the container so that it doesn't exit.
    3. Executing shell on the container and looking at the file structure.
    4. Running npm install.

    The fix:

    Ensuring the COPY command is run before npm install

    e.g.

    COPY . ./
    
    RUN npm install