Skip to content

Commit

Permalink
Merge pull request #10 from caiodearaujo/feature/docker-and-k8s
Browse files Browse the repository at this point in the history
Feature/docker and k8s
  • Loading branch information
caiodearaujo authored Sep 30, 2024
2 parents 2181707 + ca03d3e commit 74d7ff8
Show file tree
Hide file tree
Showing 13 changed files with 191 additions and 46 deletions.
37 changes: 26 additions & 11 deletions api/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,20 +1,35 @@
# Imagem base com Go
FROM golang:1.21-alpine
# Etapa de build
FROM golang:1.23.1-alpine AS builder

# Diretório de trabalho dentro do container
# Instala as dependências necessárias, incluindo o WebP
RUN apk update && apk add --no-cache libwebp-dev gcc g++ make

# Defina o diretório de trabalho
WORKDIR /app

# Copia o código-fonte para o container
COPY . .
# Copie os arquivos de dependências go.mod e go.sum
COPY ./src/go.mod ./src/go.sum ./

# Instala as dependências do projeto
# Baixe as dependências
RUN go mod download

# Compila o código Go
RUN go build -o main .
# Copie o código fonte
COPY ./src .

# Compile o binário, nomeando-o como "api"
RUN go build -o api .

# Etapa de produção
FROM alpine:3.18

# Defina o diretório de trabalho
WORKDIR /app

# Copie apenas o binário gerado do estágio anterior
COPY --from=builder /app/api /app/api

# Expõe a porta que a API irá utilizar
# Expõe a porta 8080 para acesso ao serviço
EXPOSE 8080

# Comando para iniciar a API
CMD ["./main"]
# Comando padrão para executar o binário
CMD ["/app/api"]
5 changes: 3 additions & 2 deletions api/src/conf/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package conf

import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"net/http"
"os"
"sync"

"github.com/gin-gonic/gin"
"github.com/google/uuid"
)

var (
Expand Down
6 changes: 3 additions & 3 deletions api/src/helpers/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ func getEnv(key, fallback string) string {

// Initialize a Redis client once using the sync.Once pattern to ensure a singleton instance.
func getRedisClient() *redis.Client {
redisHostname := getEnv("redis_hostname", "localhost")
redisPort := getEnv("redis_port", "6379")
redisPassword := getEnv("redis_password", "admin")
redisHostname := os.Getenv("REDIS_HOSTNAME")
redisPort := os.Getenv("REDIS_PORT")
redisPassword := os.Getenv("REDIS_PASSWORD")

redisOnce.Do(func() {
log.Info().Msg("Creating a new Redis client on dsn: " + redisHostname + ":" + redisPort)
Expand Down
17 changes: 9 additions & 8 deletions api/src/helpers/whatsapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,15 @@ type DeviceInfoResponse struct {

// ConnectToDatabase connects to the database.
func connectToDatabase() (*sqlstore.Container, error) {
dbUser := os.Getenv("pg_username")
dbPwd := os.Getenv("pg_password")
dbTCPHost := os.Getenv("pg_hostname")
dbPort := os.Getenv("pg_port")
dbName := os.Getenv("pg_database")

dbURI := fmt.Sprintf("host=%s user=%s password=%s port=%s database=%s sslmode=disable",
dbTCPHost, dbUser, dbPwd, dbPort, dbName)
dbUser := os.Getenv("PG_USERNAME")
dbPwd := os.Getenv("PG_PASSWORD")
dbTCPHost := os.Getenv("PG_HOSTNAME")
dbPort := os.Getenv("PG_PORT")
dbName := os.Getenv("PG_DATABASE")
dbSchema := os.Getenv("PG_WM_SCHEMA")

dbURI := fmt.Sprintf("host=%s user=%s password=%s port=%s database=%s search_path=%s sslmode=disable",
dbTCPHost, dbUser, dbPwd, dbPort, dbName, dbSchema)

container, err := sqlstore.New("pgx", dbURI, dbLog)
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions api/src/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"errors"
"whatsgoingon/conf"
"whatsgoingon/events"
"whatsgoingon/routes"
Expand All @@ -16,14 +15,15 @@ import (

func main() {
conf.InitToken()
r := gin.Default()
store.DeviceProps.Os = proto.String("UatzAPI")

err := godotenv.Load(".env")
if err != nil {
panic(errors.New("cannot open .env file"))
gin.SetMode(gin.ReleaseMode)
}

r := gin.Default()

// Channel for init a listener in a goroutine
myStore.CreateTablesFromDataPkg()
go events.InitListener()
Expand Down
21 changes: 7 additions & 14 deletions api/src/store/bun_pg.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,16 @@ var (
bunInstance *bun.DB
)

// Get environment variable with a fallback value.
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}

// Initialize PostgreSQL connection using environment variables.
func getPostgresConnection() (*sql.DB, error) {
dbUser := getEnv("pg_username", "postgres")
dbPwd := getEnv("pg_password", "postgres")
dbTCPHost := getEnv("pg_hostname", "localhost")
dbPort := getEnv("pg_port", "5432")
dbName := getEnv("pg_dbname", "uatzapi")
dbUser := os.Getenv("PG_USERNAME")
dbPwd := os.Getenv("PG_PASSWORD")
dbTCPHost := os.Getenv("PG_HOSTNAME")
dbPort := os.Getenv("PG_PORT")
dbName := os.Getenv("PG_DATABASE")
dbSchema := os.Getenv("PG_UA_SCHEMA")

dsn := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable", dbUser, dbPwd, dbTCPHost, dbPort, dbName)
dsn := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?search_path=%s&sslmode=disable", dbUser, dbPwd, dbTCPHost, dbPort, dbName, dbSchema)

db := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))

Expand Down
5 changes: 5 additions & 0 deletions db/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Usa a imagem base do Flyway na versão 10 com Alpine Linux
FROM flyway/flyway:10-alpine

# Define o comando padrão a ser executado quando o contêiner for iniciado
CMD ["migrate"]
2 changes: 2 additions & 0 deletions db/migrations/V1__create_initial_schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
create schema whatsmeow;
create schema uatzapi;
55 changes: 50 additions & 5 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
services:
web:
build: ./web
environment:
- APP_ENVINRONMENT=production
- APP_API_KEY_TOKEN=019242d8-d976-78ee-9744-18f7dc0c559b
ports:
- "3003:80"
depends_on:
- api

api:
build: ./api
ports:
- "8080:8080"
frontend:
build: ./frontend
ports:
- "3000:3000"
environment:
- API_KEY_TOKEN=019242d8-d976-78ee-9744-18f7dc0c559b
- PG_USERNAME=postgres
- PG_PASSWORD=postgres
- PG_HOSTNAME=postgres
- PG_PORT=5432
- PG_DATABASE=uatzapi
- PG_UA_SCHEMA=uatzapi
- PG_WM_SCHEMA=whatsmeow
- REDIS_HOSTNAME=redis
- REDIS_PORT=6379
- REDIS_PASSWORD=admin
depends_on:
- redis
- postgres
- flyway

redis:
image: redis:latest
container_name: redis
Expand All @@ -15,4 +38,26 @@ services:
volumes:
- ./redis/data:/data
command: redis-server --requirepass "admin"
restart: always
restart: always

postgres:
image: "postgres:15-alpine"
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=uatzapi
ports:
- "5432:5432"

flyway:
build:
context: ./db
environment:
- FLYWAY_URL=jdbc:postgresql://postgres:5432/uatzapi
- FLYWAY_USER=postgres
- FLYWAY_PASSWORD=postgres
volumes:
- ./db/migrations:/flyway/sql
depends_on:
- postgres
command: -connectRetries=60 migrate
2 changes: 2 additions & 0 deletions web/.env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
VITE_ENVINRONMENT=APP_ENVINRONMENT
VITE_API_KEY_TOKEN=APP_API_KEY_TOKEN
49 changes: 49 additions & 0 deletions web/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Usa a imagem base do Node.js na versão 16 e nomeia esta fase como 'build'
FROM node:16 AS build

# Define variáveis de ambiente que podem ser passadas no momento da construção da imagem
ARG APP_ENVINRONMENT
ARG APP_API_KEY_TOKEN

# Define as variáveis de ambiente com os valores recebidos dos argumentos
ENV APP_ENVINRONMENT=$APP_ENVINRONMENT
ENV APP_API_KEY_TOKEN=$APP_API_KEY_TOKEN

# Define o diretório de trabalho para o aplicativo
WORKDIR /app

# Copia os arquivos de configuração do npm para o diretório de trabalho
COPY package*.json ./

# Executa a instalação das dependências do npm
RUN npm install

# Copia todos os arquivos do projeto para o diretório de trabalho
COPY . .

# Executa o script de build do aplicativo
RUN npm run build

# Inicia uma nova fase a partir da imagem base do Nginx com Alpine
FROM nginx:alpine

# Copia os arquivos gerados na fase de build para o diretório do Nginx
COPY --from=build /app/dist /usr/share/nginx/html

# Define permissões para os arquivos copiados para o Nginx
RUN chmod -R 755 /usr/share/nginx/html

# Copia o arquivo de configuração do Nginx para o diretório apropriado
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Copia o script de configuração de ambiente para o diretório de entrada do Docker
COPY env.sh /docker-entrypoint.d/env.sh

# Torna o script copiado executável
RUN chmod +x /docker-entrypoint.d/env.sh

# Expõe a porta 80 para acesso externo
EXPOSE 80

# Comando para iniciar o Nginx em modo não daemon
CMD ["nginx", "-g", "daemon off;"]
12 changes: 12 additions & 0 deletions web/env.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/bin/sh
for i in $(env | grep APP_)
do
key=$(echo $i | cut -d '=' -f 1)
value=$(echo $i | cut -d '=' -f 2-)
echo $key=$value
# sed All files
# find /usr/share/nginx/html -type f -exec sed -i "s|${key}|${value}|g" '{}' +

# sed JS and CSS only
find /usr/share/nginx/html -type f \( -name '*.js' -o -name '*.css' \) -exec sed -i "s|${key}|${value}|g" '{}' +
done
20 changes: 20 additions & 0 deletions web/nginx.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
server {
listen 80;
server_name localhost;

location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri $uri/ /index.html; # Redireciona para index.html se o arquivo não for encontrado
}

error_page 403 /403.html;
location = /403.html {
root /usr/share/nginx/html;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

0 comments on commit 74d7ff8

Please sign in to comment.