Giter Site home page Giter Site logo

rcmonteiro / devops-create-image-nest-api Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 228 KB

Praticando a criação de uma uma imagem Docker de uma API NestJS

JavaScript 18.73% Dockerfile 14.13% TypeScript 67.14%
docker dockerfile nestjs gitactions-workflow

devops-create-image-nest-api's Introduction

Como "dockerizar" esta aplicação?

Temos uma aplicação de uma API simples, apenas um boilerplate do NESTJS.

O que ela precisa?

  • node instalado
  • instalar as dependências (npm install)
  • buildar a aplicação (npm run build)
  • iniciar a aplicação (npm start)

Podemos montar nosso Dockerfile e rodar os comandos para copiar, instalar as dependências, e então rodar a aplicação na porta que foi exposta, e é utilizada pela API, e vamos usar o pnpm como package manager

FROM node:20-slim AS base
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
COPY . /app
WORKDIR /app

FROM base AS prod-deps
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --prod --frozen-lockfile

FROM base AS build
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile
RUN pnpm run build

FROM base
COPY --from=prod-deps /app/node_modules /app/node_modules
COPY --from=build /app/dist /app/dist
EXPOSE 3000
CMD [ "pnpm", "start:prod" ]

Foi pensado em múltiplos estágios, e uso da imagem alpine para ficar com uma imagem pequena

Antes de rodar, vamos criar o .dockerignore para deixar o processo de build mais ágil:

node_modules
dist
Dockerfile
.git
.gitignore
.dockerignore
*.md

Feito isso, podemos dar o build da nossa imagem:

docker build -t api-empacotada:v1 .

Estamos usando o ".", pois temos o arquivo "Dockerfile" na raiz do nosso projeto, é lido como um "index" da pasta root do nosso projeto. (senão teria que ser passado o parâmetro -f para fazer referência ao arquivo com as instruções para buildar a imagem da aplicação)

Agora podemos rodar nossa aplicação a partir da imagem:

docker run --rm -p 3001:3000 -d api-empacotada

Usamos o --rm pois um container tem um ciclo de vida, então quando ele for parado ele é excluído.abs, não passando este parâmetro, o container fica disponível na máquina para rodar novamente outra vez. Também usamos a porta 3001 para ficar claro que estamos acessando a aplicação pelo docker, e não pelo ambiente local do host.

E pronto, tudo certo! Temos nossa aplicação NestJS empacotada em uma imagem docker!

⟩ http GET :3001/
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 12
Content-Type: text/html; charset=utf-8
Date: Tue, 07 May 2024 14:57:06 GMT
ETag: W/"c-Lve95gjOVATpfV8EL5X4nxwjKHE"
Keep-Alive: timeout=5
X-Powered-By: Express

Hello World!

Com um banco de dados como dependência, para rodar local, fica bacana usar o docker-compose, ficando bem prático para subir o ambiente local usando a nossa imagem da aplicação que criamos pelo Dockerfile:

services:
  mysql:
    image: mysql:8
    container_name: mysql
    ports:
      - 3306:3306
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=rocketseat-db
      - MYSQL_USER=admin
      - MYSQL_PASSWORD=root
    networks:
      - first-network
  
  sample-api:
    build:
      context: .
    container_name: sample-api
    ports:
      - 3001:3000
    depends_on:
      - mysql
    networks:
      - first-network

networks:
  first-network:
    driver: bridge

devops-create-image-nest-api's People

Contributors

rcmonteiro avatar semantic-release-bot avatar

Stargazers

Jonathan avatar

Watchers

 avatar

devops-create-image-nest-api's Issues

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Cannot push to the Git repository.

semantic-release cannot push the version tag to the branch main on the remote Git repository with URL https://x-access-token:[secure]@github.com/rcmonteiro/devops-create-image-nest-api.

This can be caused by:


Good luck with your project ✨

Your semantic-release bot 📦🚀

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.