# Dockerizing a Node.js web application

## Build the Node.js application

Firstly, create Dockerfile for the Node.js application.

```dockerfile
FROM node:14.18.2-alpine3.14
WORKDIR /app
COPY package.json ./
COPY package-lock.json ./
COPY ./ ./
RUN npm ci
CMD ["npm", "run", "start"]
```

Since I've used *node-sass* package for enabling SASS in my application and [the package supports limited Node.js version](https://github.com/sass/node-sass/releases/), I need to find the right [node.js docker image at **docker hub**](https://hub.docker.com/_/node).

![Supported Environments by node-sass package](https://cdn.hashnode.com/res/hashnode/image/upload/v1639834675706/Hh0CxC1vg.png align="left")

At *docker hub*, search for the right image in the *Tags* tab. Once the desired image is found, put it on the first line (i.e. the FROM layer) of the Dockerfile.

![Node.js docker images](https://cdn.hashnode.com/res/hashnode/image/upload/v1639834697621/GMFQlAgQ6.png align="left")

Secondly, create .dockerignore file to exclude files and directories from the docker image.

```yaml
node_modules
*.log
```

Thirdly, build the Node.js application.

```sh
yarn build
```

Fourthly, build the docker image.

\**Make sure Docker Engine is running in your development environment.*

```sh
docker build -f Dockerfile -t portfolio-website .
```

## Deployment

* Deploy by exposing port 5001 instead of default port 3000 (you can change to any port according to your environment).
    

```sh
docker run --name portfolio-website -it -p 5001:3000 portfolio-website
```

## Verification

* Check that the web application is running by opening `http://localhost:5001/` in a web browser.
    

![Dockerized Node.js application](https://cdn.hashnode.com/res/hashnode/image/upload/v1639834732247/A4vCws9T0.png align="left")
