To build and start the project utilizing the docker/build-push-action
, follow the steps below, providing detailed code examples to guide you through the process.
Prerequisites
Ensure that your environment is set up with the following:
- Docker installed on your machine.
- GitHub Actions configured for your repository.
- The necessary permissions to run workflows.
Step 1: Directory Structure
Your project should have a structure similar to the following:
.
├── Dockerfile
├── go/
│ └── main.go
├── typescript/
│ └── index.ts
└── hcl/
└── config.hcl
Step 2: Create a Dockerfile
The Dockerfile
is essential for building the container image. Here is an example Dockerfile that compiles TypeScript and Go code.
# Start from the official Golang base image
FROM golang:1.17 AS builder
# Set the working directory
WORKDIR /app
# Copy Go source code
COPY go/ ./go
COPY go.mod ./
COPY go.sum ./
# Build the Go application
RUN go build -o myapp ./go/
# Start a new stage from the official Node.js image
FROM node:14 AS frontend
# Set working directory
WORKDIR /frontend
# Copy TypeScript source code
COPY typescript/ ./typescript
# Install TypeScript and build the TypeScript application
RUN npm install -g typescript && tsc ./typescript/index.ts
# Final stage to run the application
FROM scratch
# Copy binaries from builder
COPY --from=builder /app/myapp /myapp
COPY --from=frontend /frontend/typescript/index.js /index.js
# Command to run the application
ENTRYPOINT ["/myapp"]
Step 3: GitHub Actions Workflow Configuration
Create a GitHub Actions workflow file at .github/workflows/build-and-push.yml
.
name: Build and Push
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Build and push Docker image
uses: docker/build-push-action@v2
with:
push: true
tags: your-docker-repo/your-image:latest
Step 4: Building the Project
After setting up the workflow, push your changes to the main
branch. The GitHub Actions workflow will automatically trigger and build the Docker image.
To manually build and test the Docker image locally, run the following command from the project root:
docker build -t your-docker-repo/your-image .
Step 5: Running the Project
Once the Docker image is built successfully, you can run the container using:
docker run -d --name myapp-container your-docker-repo/your-image
Step 6: Accessing the Application
If your application exposes particular ports, make sure to map them during the run command, for example:
docker run -d -p 8080:8080 --name myapp-container your-docker-repo/your-image
You can access the application in your web browser at http://localhost:8080
.
Step 7: Stopping and Removing the Container
To stop and remove the container after testing, run:
docker stop myapp-container
docker rm myapp-container
Ensure you replace your-docker-repo/your-image
with the relevant repository and image names to suit your project.
Source: the code base of the project and GitHub Actions documentation.