Modif DevOps Pipeline

This commit is contained in:
corenthin 2025-11-27 12:45:06 +01:00
parent 2deb3639ec
commit eba5817ae5
6 changed files with 229 additions and 1 deletions

2
.env.development Normal file
View File

@ -0,0 +1,2 @@
VITE_API_BASE_URL=http://127.0.0.1:3000

2
.gitignore vendored
View File

@ -29,8 +29,8 @@ dist/
.env.development.local
.env.test.local
.env.production.local
.env.development
.env.production
.env
# Editor directories and files

25
DOCKER_README.md Normal file
View File

@ -0,0 +1,25 @@
# Docker Development Setup
To build and run the Docker container locally:
1. **Build the image**:
You need to pass the `VITE_API_BASE_URL` as a build argument because Vite bakes environment variables into the static files at build time.
```bash
docker build \
--build-arg VITE_API_BASE_URL=http://localhost:3000/api \
-t frontend-solyti .
```
2. **Run the container**:
```bash
docker run -p 8080:80 frontend-solyti
```
The application will be accessible at `http://localhost:8080`.
## Notes on Environment Variables
Since this is a client-side application (React/Vite), environment variables like `VITE_API_BASE_URL` are replaced during the `npm run build` process. They are **not** read from the server's environment at runtime (unlike a Node.js backend).
If you need to change the API URL for different environments (dev, staging, prod) without rebuilding the Docker image, you would need a runtime configuration strategy (e.g., loading a `config.js` file at runtime), but the current setup follows the standard "build-time bake" approach for simplicity and performance.

42
Dockerfile Normal file
View File

@ -0,0 +1,42 @@
# Stage 1: Dependencies
FROM node:20-alpine AS deps
WORKDIR /app
# Install dependencies only when needed
COPY package.json package-lock.json ./
RUN npm ci
# Stage 2: Builder
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Build the application
# We use a build argument to pass the API URL at build time if needed,
# or it can be overridden at runtime for the preview/dev server if we were serving that.
# However, for a static build served by Nginx, env vars are baked in at build time.
ARG VITE_API_BASE_URL
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
RUN npm run build
# Stage 3: Runner (Nginx for serving static files)
FROM nginx:alpine AS runner
# Remove default nginx website
RUN rm -rf /usr/share/nginx/html/*
# Copy built assets from builder stage
COPY --from=builder /app/dist /usr/share/nginx/html
# Copy custom nginx config
# We will create this file in the next step
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Expose port 80
EXPOSE 80
# Start Nginx
CMD ["nginx", "-g", "daemon off;"]

133
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,133 @@
// Pipeline Jenkins pour le dépôt Frontend
// Déclenchée lors d'un push sur la branche 'dev'
// Objectif : Construire une image Docker, la déployer sur une VM
pipeline {
// Les options de construction et le déclencheur
options {
// Option pour annuler automatiquement les builds précédentes en cours
disableConcurrentBuilds()
}
// Définition de l'agent (exécuteur) de Jenkins
agent any
// Paramètres qui devront être définis dans Jenkins (gérés comme des secrets)
// Ces identifiants doivent être configurés dans Jenkins.
environment {
// Nom du service Docker (à adapter)
SERVICE_NAME = 'AutoDeploy'
// Registre Docker cible (ex: votre Gitea Registry, Docker Hub, ou un registre privé)
// Remplacez par votre registre. Par exemple : 'registry.votre-domaine.com/frontend'
DOCKER_REGISTRY_URL = 'gitea.firewax.fr/corenthin/test:latest'
// Hôte de déploiement (la VM contenant l'outil d'exécution)
DEPLOY_HOST = '172.75.13.5'
// Identifiant Jenkins pour l'accès SSH à la VM de déploiement (doit exister dans Jenkins)
// REMPLACÉ PAR UN ID NUMÉRIQUE SELON VOTRE DEMANDE
DEPLOY_CREDENTIALS_ID = '1000'
}
triggers {
// Le déclenchement est maintenant géré par le Generic Webhook Trigger configuré dans l'interface du Job.
// On retire pollSCM('') car il n'est plus pertinent.
}
stages {
stage('Checkout Code') {
steps {
// Récupération du code source depuis Gitea
// Nous utilisons 'scm' qui est configuré dans le Job,
// et Jenkins s'occupe de checkout la branche qui a déclenché le build.
checkout scm
}
}
stage('Build Docker Image') {
steps {
script {
// Création d'un tag basé sur le hachage de commit court (pour unicité)
def shortCommit = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
// Tag complet de l'image
env.IMAGE_TAG = "${env.DOCKER_REGISTRY_URL}:${shortCommit}"
// --- NOUVEAU: Injection des variables d'environnement sécurisées ---
// Ceci suppose que vous avez un Credential ID 'frontend-api-url-secret' de type Secret Text
withCredentials([string(credentialsId: 'frontend-api-url-secret', variable: 'API_URL')]) {
// Construction de l'image Docker en passant la variable secrète comme build-arg
echo "Construction de l'image Docker avec le tag : ${env.IMAGE_TAG}"
// L'argument --build-arg est utilisé pour injecter la variable pendant le build
sh "docker build -t ${env.IMAGE_TAG} --build-arg API_URL=${API_URL} ."
// NOTE IMPORTANTE: Le secret ${API_URL} n'est PAS affiché dans la console du build grâce à withCredentials.
}
// -------------------------------------------------------------------
}
}
}
stage('Push Docker Image') {
steps {
// Authentification au registre Docker (nécessite un Credential ID 'docker-registry-credentials')
// Ce Credential ID doit contenir les identifiants pour se connecter au registre.
withCredentials([usernamePassword(credentialsId: 'docker-registry-credentials', passwordVariable: 'DOCKER_PASSWORD', usernameVariable: 'DOCKER_USERNAME')]) {
sh "echo \$DOCKER_PASSWORD | docker login -u \$DOCKER_USERNAME --password-stdin ${env.DOCKER_REGISTRY_URL.substring(0, env.DOCKER_REGISTRY_URL.indexOf('/'))}"
// Push de l'image
sh "docker push ${env.IMAGE_TAG}"
// Nettoyage de l'image locale après le push
sh "docker rmi ${env.IMAGE_TAG}"
}
}
}
stage('Deploy on VM') {
steps {
// Utilisation du plugin SSH Agent (ou SSH Pipeline Steps) pour se connecter à la VM.
// Assurez-vous d'avoir le plugin 'SSH Agent' installé dans Jenkins.
sshagent(credentials: [env.DEPLOY_CREDENTIALS_ID]) {
// Script de déploiement à exécuter sur la VM
def deployScript = """
# 1. Pull de la nouvelle image
docker pull ${env.IMAGE_TAG}
# 2. Arrêt du container existant (si il existe)
if [ \$(docker ps -a -q -f name=${env.SERVICE_NAME}) ]; then
echo "Arrêt du container existant..."
docker stop ${env.SERVICE_NAME}
docker rm ${env.SERVICE_NAME}
fi
# 3. Lancement du nouveau container
echo "Démarrage du nouveau container..."
docker run -d --name ${env.SERVICE_NAME} -p 80:80 ${env.IMAGE_TAG}
# 4. Nettoyage des anciennes images
docker image prune -f --filter "until=24h"
"""
// Exécution du script via SSH sur la VM de déploiement
sh "ssh -o StrictHostKeyChecking=no user@${env.DEPLOY_HOST} \"${deployScript}\""
}
}
}
stage('Cleanup') {
steps {
// Nettoyage de l'espace de travail local sur le runner Jenkins
cleanWs()
}
}
}
// Actions post-build (à adapter)
post {
always {
// Envoi de notifications, archivage des artefacts, etc.
echo "Pipeline Frontend terminée pour le commit: ${env.IMAGE_TAG}"
}
failure {
echo '!!! ÉCHEC de la pipeline Frontend !!!'
}
}
}

26
nginx.conf Normal file
View File

@ -0,0 +1,26 @@
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Gzip compression
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
location / {
try_files $uri $uri/ /index.html;
}
# Cache control for static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, no-transform";
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}