简体   繁体   中英

Run and compile code inside a Docker container

Please follow this reasoning and tell me where I am wrong.

  • I want to develop a web app with Typescript. This is the folder structure:
src
- index.ts
package.json
tsconfig.json
  • I want to compile and run the app inside a container so that is not environment-dependent.

  • I run docker build --name my_image with the following Dockerfile in order to create an image:

FROM node:16
WORKDIR /app
COPY package.json /app
RUN npm install
CMD ["npx", "dev"]
  • This will create a node_modules folder inside the container.

  • Now I create a container like so:

docker create -v $(pwd)/src/:/app/src my_image --name my_container
  • I created a volume so that when I change files in my host /src I will change also the same files in the container.

  • I start the container like so:

docker start -i my_container
  • Now everything is working. The problem, though, are the linters.

  • When I open a file with my text editor from the host machine in /src the linter are not working because there is no node_modules installed on the host.

If I npm install also on the host machine I will have 2 different node_modules installation and there might be some compilation that differ between the host and the container.

Is there a way to point the host node_modules to the container node_modules ?

If I create a docker volume for node_modules like so

docker create -v $(pwd)/node_modules:/app/node_modules ...

I will delete all the compilation done in the container.

What am I doing wrong?

Thank you.

For those who might have a similar problem, this is what I have done and it is working.

First I build an image:

docker build --name my_image .

Then I copy the node_modules folder from a temporary container to my local folder:

docker create --name tmp_container my_image
docker cp tmp_container:/app/node_modules ./node_modules
docker rm tmp_container

Then I create the final container with a volume:

docker create -v $(pwd)/node_modules:/app/node_modules --name my_container my_image

And now I have a exactly what it has built and compiled in the container but also in my local folder.

This can be of course extended to any folder with build artifacts. For example in my case I needed also another folder in order to make the linters work in my text editor. I just copy the folder exactly like I did with node_modules .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM