Day 17 : Docker Project for DevOps Engineers
Anand Raval
CSE Undergraduate | 2x AWS Certified Solution Architect Associate,CCP | Aspiring Cloud and DevOps | Docker | Kubernetes | Linux | Git, GitHub & GitLab | Jenkins | GCP | Application Testing & Deployment | Content Writer
Day 17 Task:
Dockerfile
Docker is a tool that makes it easy to run applications in containers. Containers are like small packages that hold everything an application needs to run. To create these containers, developers use something called a Dockerfile.
A Dockerfile is like a set of instructions for making a container. It tells Docker what base image to use, what commands to run, and what files to include. For example, if you were making a container for a website, the Dockerfile might tell Docker to use an official web server image, copy the files for your website into the container, and start the web server when the container starts.
For more about Dockerfile, visit here.
Task
To write a Dockerfile, follow these steps:
Here is an example Dockerfile for a simple Node.js application:
# Use the official Node.js image as the base image
FROM node:14
# Set the working directory inside the container
WORKDIR /app
# Copy package.json and package-lock.json to the working directory
COPY package*.json ./
# Install the dependencies
RUN npm install
# Copy the rest of the application files to the working directory
COPY . .
# Expose port 3000
EXPOSE 3000
# Define the command to run the application
CMD ["node", "app.js"]
Explanation of each line:
To build and run the Docker container:
Replace your-dockerhub-username with your actual Docker Hub username.
plaintextCopy codeFlask==2.0.3
Werkzeug==2.0.3
Rebuild Docker Image
After updating the requirements.txt file, rebuild your Docker image to install the correct versions of the dependencies.
领英推荐
bashCopy codedocker build -t tic-tac-toe .
Verify Updated requirements.txt
Ensure your requirements.txt looks like this:
plaintextCopy codeFlask==2.0.3
Werkzeug==2.0.3
Full Directory Structure and File Contents
Ensure your project directory structure and file contents are correct:
Directory Structure
plaintextCopy codetic_tac_toe/
├── app/
│ ├── __init__.py
│ ├── routes.py
│ └── static/
│ └── style.css
│ └── templates/
│ └── index.html
├── Dockerfile
├── requirements.txt
└── run.py
app/__init__.py
pythonCopy codefrom flask import Flask
app = Flask(__name__)
from app import routes
app/routes.py
pythonCopy codefrom flask import render_template, request, jsonify
from app import app
@app.route('/')
def index():
return render_template('index.html')
@app.route('/make_move', methods=['POST'])
def make_move():
data = request.get_json()
board = data['board']
player = data['player']
# Here you should add the logic to check for a win or draw.
result = {'status': 'ongoing'} # This is just a placeholder.
return jsonify(result)
app/templates/index.html
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic Tac Toe</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Tic Tac Toe</h1>
<div id="board"></div>
<script>
const player = 'X'; // This should switch between 'X' and 'O' in actual game logic.
let board = Array(9).fill(null);
function createBoard() {
const boardDiv = document.getElementById('board');
boardDiv.innerHTML = '';
board.forEach((cell, index) => {
const cellDiv = document.createElement('div');
cellDiv.classList.add('cell');
cellDiv.dataset.index = index;
cellDiv.addEventListener('click', () => makeMove(index));
cellDiv.textContent = cell;
boardDiv.appendChild(cellDiv);
});
}
function makeMove(index) {
if (board[index]) return;
board[index] = player;
createBoard();
fetch('/make_move', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ board, player }),
})
.then(response => response.json())
.then(data => {
if (data.status === 'win') {
alert(`${player} wins!`);
} else if (data.status === 'draw') {
alert('Draw!');
} else {
// Switch player and continue
}
});
}
createBoard();
</script>
</body>
</html>
app/static/style.css
cssCopy codebody {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
h1 {
margin-bottom: 20px;
}
#board {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-gap: 10px;
}
.cell {
width: 100px;
height: 100px;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
background-color: #f0f0f0;
cursor: pointer;
}
run.py
pythonCopy codefrom app import app
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True)
Dockerfile
DockerfileCopy code# Use an official Python runtime as a parent image
FROM python:3.8-slim
# Set the working directory
WORKDIR /app
# Copy the current directory contents into the container
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make port 5000 available to the world outside this container
EXPOSE 5000
# Run app.py when the container launches
CMD ["python", "run.py"]
requirements.txt
plaintextCopy codeFlask==2.0.3
Werkzeug==2.0.3
Rebuild and Run the Docker Container