I have been using asdf
, a version manager for every tool (e.g. Node,js, Ruby, MySQL, you name it) for years.
It was great since I could manage multiple versions of the same tool.
I could switch between versions easily.
I could even have different versions of the same tool in different projects.
There is nothing wrong with asdf
.
I thought to myself, "Is there a way to serve my web applications more efficiently?"
Since I've been tinkering with Docker, maybe I could serve my web app with Docker
and mount the working directory to the container so that any changes I make in the working directory
would reflect in the container.
By serving the web app with a container, I do not have to go to the working directory, run and stop the server. As soon as I turn on my computer, the server is already running.
To do this, we need two files: docker-compose.yml
and webapp.dockerfile
. Then go to your working directory and create those two files.
FROM node:current-alpine3.19
WORKDIR /home/webapp
COPY . /home/webapp
RUN npm install
CMD ["npm", "run", "dev"]
FROM node:current-alpine3.19
- This line tells Docker that we want to use the node
image with the tag current-alpine3.19
.WORKDIR /home/webapp
- This line tells Docker to set the working directory to /home/webapp
.COPY . /home/webapp
- This line tells Docker to copy everything in the working directory to /home/webapp
.RUN npm install
- This line tells Docker to run npm install
in the container.CMD ["npm", "run", "dev"]
- This line tells Docker to run npm run dev
in the container.By default, Next.js web applications are served on port 3000.
services:
webapp:
build:
context: .
dockerfile: webapp.dockerfile
container_name: webapp
volumes:
- /path/to/your/webapp:/home/webapp
restart: always
ports:
- 9999:3000
webapp:
- This is the name of the service.build:
- This tells Docker to build the image.context: .
- This tells Docker to use the current directory you defined in Dockerfile
above.dockerfile: webapp.dockerfile
- This tells Docker to use the webapp.dockerfile
we just defined above.container_name: webapp
- This is the name of the container, you could name whatever you like.volumes:
- This tells Docker to mount the working directory to the container. (Use pwd
on your terminal if you are sure about the path you're currently on).restart: always
- This tells Docker to restart the container if it crashes.ports:
- This tells Docker to map the port 3000 in the container to the port 9999 on your computer. You could change 9999 to whatever number you like.To start the server, run docker compose up -d
in your terminal. -d
means detached mode, meaning the container will run in the background.
To make sure, go to your browser and access http://localhost:9999
.