Can we build a node application without installing node locally? We sure can! Lets walk through the process.
First make sure that docker is installed. This is handy if you are working on a remote server for example.
Then lets start building out the
Dockerfile that we will use.
- Create a
- Start up the container with
This is going to download the
node:14 docker image, and start a shell.
Lets build and start it a temporary container that has our new directory mounted in there and run the
npx create-react-app . command, which will generate the new app.
Once this is done, you should see a basic
create-react-app generated folder in your local
testapp directory. We need to adjust some permissions here since it’s probably owned by root.
Revel in our generated node_modules!
node_modules so lets delete it.
Setting up for development
If you keep the
node_modules directory around you may have some cross platform issues.
node_modules directory may contain native code, which would be built against the libraries inside of the docker container. If you are running the same OS as what’s inside of the container – Linux – then you can have these co-mingle, but if you are on OSX this is potentially a pain.
What we are going to do is use a docker volume to hide all of this away so we never need to see it and worry about it poluting our machine. Make sure you’ve deleted that terrible folder!
Lets create a
testapp/Dockerfile to run the app itself out of the local directory:
- First we copy over package.json and yarn.lock into /app. If these files ever change, we will rerun all of the following steps when building the container.
yarn installto install the local
- Expose port
3000which is the development server port.
- We’ll create a docker volume to hide the mess away.
And create a script that will build and start up the container easily, called
Now lets fire up a development server using
testapp/src/App.js, make a change, and revel in the automatic reloading!
Adding a library
Kill the server with
C-c. Lets go through the process of adding a library.
In the first step, you see things get downloaded from the internet. If you look at your
package.json file after it will be updated with the dependancy. The second time we run the
start.sh script it will notice that
package.json changed and rerun
yarn install, but since we have mounted
node_modules in a volume it doesn’t need to pull anything more from the internet.
Lets edit our
App.js file to use the new component to make sure that it works.
After a few seconds you should see the basic globe demo appear in your browser. Love that globe.
This is done simply by
The container that we use is temporary, and gets cleaned up after you exit out. But we still have the docker image and docker volume floating around –
node_modules is always out to get you! – so we’ll need to clean that up after. You can delete this with:
The next time you run
start.sh this will all get recreated.