
Let's say something like this is being returned when attempting to run your Node.js Docker container.
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'dotenv' imported from /src/server.js
Notice in this example that the dotenv package cannot be found. This is typically resolved by using the npm install command to install the package when building the image from a Dockerfile. For example, your Dockerfile could have something like this.
FROM node:18-alpine
RUN npm install dotenv
CMD ["npm", "start"]
More commonly, the packages are listed as "dependencies" in your package.json file, perhaps something like this.
{
"dependencies": {
"dotenv": "^16.0.0"
}
}
And then your Dockerfile would use the npm install command to install the "dependencies" in your package.json file.
FROM node:18-alpine
WORKDIR /src/
COPY package.json /src/
RUN npm install
CMD ["npm", "start"]
The docker run command can then be used to list the Node packages in the image.
]$ sudo docker run -it --rm <your Docker image> npm list
@johndoe /src
+-- dotenv@16.0.3
+-- express@4.18.2
`-- node-fetch@3.3.1
Notice in the above example that the packages have been installed in the /src directory. You can list the contents of the /src directory in the image and there should be a node_modules directory that contains the installed modules, and also package.json and package-lock.json.
]$ sudo docker run -it --rm <your Docker image> ls -l /src
total 36
drwxr-xr-x 69 root root 4096 May 22 07:11 node_modules
-rw-r--r-- 1 root root 26405 May 22 07:11 package-lock.json
-rw-r--r-- 1 root root 416 May 22 07:11 package.json
When creating the container using the docker run command, do not use the --volume option to overwrite the directory that contains the node_modules directory. For example, this command would overwrite the /src directory in the container with the contents of the /path/to/local/directory on the Docker host.
sudo docker run --volume /path/to/local/directory:/src example:latest
Did you find this article helpful?
If so, consider buying me a coffee over at