Hello to all the readers!
There is another concept of bind mounts in docker that allows to share the host machine directory inside docker. The contents changed on the host machine or inside docker are reflected on both sides.
Here is how to use a bind mount.
docker run -it --mount type=bind,src="$(pwd)",target=/src ubuntu bash
root@d39a8b9c0be8:/# ls -l /src
total 152
-rw-r--r-- 1 1000 1000 113 Jun 22 05:13 Dockerfile
-rw-r--r-- 1 1000 1000 645 Jun 22 05:10 package.json
drwxr-xr-x 4 1000 1000 80 Jun 22 05:10 spec
drwxr-xr-x 5 1000 1000 120 Jun 22 05:10 src
-rw-r--r-- 1 1000 1000 147266 Jun 22 05:10 yarn.lock
root@d39a8b9c0be8:/#
Now if we make changes in this directory either on host or inside container, it will reflect on both sides.
The biggest advantage of bind mount is for local development setup.
Example of Bind Mount
We will use the getting-started image to run the container.
docker run -dp 3000:3000 -w /app --mount type=bind,src="$(pwd)",target=/app node:18-alpine sh -c "yarn install && yarn run dev"
“-w” tells the working directory where the shell command will run inside. yarn runs the dev script defined in package.json.
"scripts": {
"prettify": "prettier -l --write \"**/*.js\"",
"test": "jest",
"dev": "nodemon src/index.js"
},
nodemon watches the filesystem for changes in files and auto reloads the app.
We can see the logs of the container by using
docker logs -f 558e128c6b89
yarn install v1.22.19
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
Done in 12.87s.
yarn run v1.22.19
$ nodemon src/index.js
[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node src/index.js`
Using sqlite database at /etc/todos/todo.db
Listening on port 3000
If we make a change in script, then nodemon restarts the app like this.
[nodemon] restarting due to changes...
[nodemon] starting `node src/index.js`
Using sqlite database at /etc/todos/todo.db
Listening on port 3000