diff --git a/Dockerfile b/Dockerfile index 511d3651..bc8c8122 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,19 +1,20 @@ -FROM node:24-alpine +# Used stable version-LTS +FROM node:20-alpine -# Create app user and group -RUN addgroup app && adduser -S -G app app +# Set working directory inside container +WORKDIR /app -WORKDIR /usr/src/app - -# Copy package files and install dependencies as root +# Copy package files first COPY package*.json ./ -RUN npm ci --omit=dev -# Copy rest of the app -COPY . . +# Install dependencies-into image +RUN npm install -# Switch to non-root user for runtime -USER app +# Copy remaining files +COPY . . +# Expose application port inside container EXPOSE 3000 -CMD ["node", "app.js"] +# Start the script inside package.json-when container runs +CMD ["npm", "start"] + diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 00000000..25a91e48 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,53 @@ + pipeline { + agent any // In this case windows local + + environment { // for reusability and clean code + IMAGE_NAME = "my-node-app2" + CONTAINER_NAME = "node-app-container2" + PORT = "3000" + } + + stages { // contains all phases of CI-CD pipeline + + stage('Pull Code') { + steps { + git( // provided by git plugins + branch: 'dev', + url: 'https://github.com/harshitmishra25/sample-node-project' + ) + } + } + + stage('Build Docker Image') { + steps { // image + bat 'docker build -t %IMAGE_NAME% .' + } + } + + stage('Stop & Remove Old Container') { + steps { + bat ''' + docker stop %CONTAINER_NAME% || exit 0 + docker rm %CONTAINER_NAME% || exit 0 + ''' + } + } + + stage('Run Docker Container') { + steps { // container + bat ''' + docker run -d -p %PORT%:%PORT% --name %CONTAINER_NAME% %IMAGE_NAME% + ''' + } + } + } + + post { // runs after pipeline finishes(success/failure) + success { + echo "Pipeline completed successfully" + } + failure { + echo "Pipeline failed" + } + } +} \ No newline at end of file