-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDockerfile.database
More file actions
255 lines (216 loc) · 7.35 KB
/
Dockerfile.database
File metadata and controls
255 lines (216 loc) · 7.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# Pro-Mata Base Database Container with PostgreSQL and Prisma Migration
FROM postgres:16-alpine
# Metadata labels
LABEL org.label-schema.name="pro-mata-database-base" \
org.label-schema.description="Base PostgreSQL image with Prisma migration support for Pro-Mata" \
org.label-schema.vendor="AGES PUCRS" \
org.label-schema.version="16-alpine-base"
# Install Node.js for Prisma migrations and additional tools
RUN apk add --no-cache \
nodejs \
npm \
postgresql-client \
postgresql-contrib \
openssl \
libc6-compat \
netcat-openbsd \
curl \
bash \
tzdata \
gzip \
procps
# Set timezone to Brazil
RUN cp /usr/share/zoneinfo/America/Sao_Paulo /etc/localtime && \
echo "America/Sao_Paulo" > /etc/timezone
# Set default PGDATA location (can be overridden)
ENV PGDATA=/var/lib/postgresql/data/pgdata
ENV TZ=America/Sao_Paulo
ENV PGTZ=America/Sao_Paulo
# Create app directory for migration scripts
WORKDIR /app
# Copy package files and prisma schema
COPY package*.json ./
COPY prisma ./prisma/
# Install only production dependencies needed for migrations
RUN npm ci --only=production && npm cache clean --force
# CORREÇÃO: Adicionar try-catch para prisma generate
RUN npx prisma generate || echo "⚠️ Prisma generate failed during build, will retry at runtime"
# Create basic initialization script (database-specific initialization to be handled by extending images)
COPY <<'EOF' /docker-entrypoint-initdb.d/00-base-init.sh
#!/bin/bash
set -e
echo "🚀 Pro-Mata Base Database Initialization"
echo "Timestamp: $(date)"
echo "PostgreSQL Version: $(postgres --version)"
echo "Timezone: $(date +'%Z %z')"
# Create directory structure for extensibility
mkdir -p /var/lib/postgresql/scripts
mkdir -p /var/lib/postgresql/backups
mkdir -p /etc/postgresql/conf.d
# Set proper permissions
chown -R postgres:postgres /var/lib/postgresql/scripts
chown -R postgres:postgres /var/lib/postgresql/backups
echo "✅ Base database initialization completed!"
EOF
# Create improved migration script
COPY <<'EOF' /app/migrate.sh
#!/bin/bash
set -e
echo "🔄 Pro-Mata Database Migration Tool"
echo "Environment: ${NODE_ENV:-development}"
echo "Database Host: ${POSTGRES_HOST:-localhost}"
echo "Database Port: ${POSTGRES_PORT:-5432}"
# Validate required environment variables
if [ -z "$DATABASE_URL" ] && [ -z "$POSTGRES_USER" ]; then
echo "❌ Error: DATABASE_URL or POSTGRES_USER must be set"
exit 1
fi
# Wait for PostgreSQL to be ready
echo "⏳ Aguardando PostgreSQL..."
until pg_isready -h ${POSTGRES_HOST:-localhost} -p ${POSTGRES_PORT:-5432} -U ${POSTGRES_USER:-postgres}; do
echo " Banco não disponível, tentando novamente..."
sleep 2
done
echo "✅ PostgreSQL disponível!"
# Use DATABASE_URL if provided, otherwise construct from parts
if [ -z "$DATABASE_URL" ]; then
export DATABASE_URL="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST:-localhost}:${POSTGRES_PORT:-5432}/${POSTGRES_DB}?schema=public"
fi
# CORREÇÃO: Regenerar Prisma Client antes de conectar
echo "🔄 Regenerando Prisma Client..."
npx prisma generate
# Check database connection with Prisma
echo "Verificando conexão com Prisma..."
if ! node -e "
const { PrismaClient } = require('@prisma/client');
new PrismaClient().\$connect()
.then(() => {
console.log('Prisma conectado com sucesso!');
process.exit(0);
})
.catch(e => {
console.error('Erro na conexão Prisma:', e.message);
process.exit(1);
})
"; then
echo "Falha na conexão com banco via Prisma"
exit 1
fi
# Create backup if in production
if [ "$NODE_ENV" = "production" ]; then
echo "Criando backup de segurança..."
BACKUP_FILE="/var/lib/postgresql/backups/backup-$(date +%Y%m%d-%H%M%S).sql"
if pg_dump "${DATABASE_URL}" > "$BACKUP_FILE" 2>/dev/null; then
echo "Backup criado: $BACKUP_FILE"
# Compress backup
gzip "$BACKUP_FILE"
echo "Backup comprimido: ${BACKUP_FILE}.gz"
else
echo "Backup falhou, continuando com migrações..."
fi
fi
# Check migration status
echo "Verificando status das migrações..."
if npx prisma migrate status; then
echo "Status das migrações verificado"
else
echo "Problemas no status das migrações, tentando resolver..."
# MELHORIA: Tentar resolver problemas automaticamente
npx prisma migrate resolve --applied || echo "Não foi possível resolver automaticamente"
fi
# Deploy migrations
echo "Executando migrações..."
if npx prisma migrate deploy; then
echo "Migrações executadas com sucesso!"
else
echo "Erro ao executar migrações!"
exit 1
fi
# Seed database if requested or in development
if [ "$RUN_SEED" = "true" ] || [ "$NODE_ENV" = "development" ]; then
echo "Executando seed do banco..."
if npx prisma db seed; then
echo "Seed executado com sucesso!"
else
echo "Seed não disponível ou falhou, tentando script direto..."
if [ -f "prisma/seed.js" ]; then
node prisma/seed.js
else
echo "Arquivo seed.js não encontrado"
fi
fi
fi
# Final verification
echo "Verificação final da conectividade..."
if node -e "
const { PrismaClient } = require('@prisma/client');
new PrismaClient().\$connect()
.then(() => {
console.log('Verificação final: Conexão OK');
process.exit(0);
})
.catch(e => {
console.error('Verificação final falhou:', e.message);
process.exit(1);
})
"; then
echo "Migration container completado com sucesso!"
else
echo "Verificação final falhou!"
exit 1
fi
EOF
# Create improved startup script
COPY <<'EOF' /app/start-database.sh
#!/bin/bash
set -e
echo "🚀 Starting Pro-Mata Database Container..."
# Check if running as migration-only mode
if [ "$MIGRATION_MODE" = "true" ]; then
echo "🔄 Running in migration-only mode"
/app/migrate.sh
exit 0
fi
# Start PostgreSQL in background
echo "🗄️ Starting PostgreSQL..."
docker-entrypoint.sh postgres &
PG_PID=$!
# Wait for PostgreSQL to be ready with better retry logic
echo "⏳ Waiting for PostgreSQL to be ready..."
retry_count=0
max_retries=30
until pg_isready -h localhost -p 5432 -U ${POSTGRES_USER:-postgres} || [ $retry_count -eq $max_retries ]; do
echo " PostgreSQL não pronto, tentativa $((retry_count + 1))/$max_retries"
sleep 2
retry_count=$((retry_count + 1))
done
if [ $retry_count -eq $max_retries ]; then
echo "❌ PostgreSQL não ficou disponível após $max_retries tentativas"
exit 1
fi
# Run migrations if AUTO_MIGRATE is enabled
if [ "$AUTO_MIGRATE" = "true" ]; then
echo "🔄 Running automatic migrations..."
/app/migrate.sh
fi
# Keep PostgreSQL running in foreground
echo "✅ Database ready! PostgreSQL running."
wait $PG_PID
EOF
# Make scripts executable
RUN chmod +x /docker-entrypoint-initdb.d/00-base-init.sh
RUN chmod +x /app/migrate.sh
RUN chmod +x /app/start-database.sh
# Create default directories for extending images
RUN mkdir -p /etc/postgresql/conf.d \
/var/lib/postgresql/backups \
/var/lib/postgresql/scripts
# Expose PostgreSQL port
EXPOSE 5432
# Improved health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
CMD pg_isready -h localhost -p 5432 -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-postgres} || exit 1
# Use the startup script as entrypoint
ENTRYPOINT ["/app/start-database.sh"]
# Default command (can be overridden by extending images)
CMD []