Deploy Code Using a Docker Compose File
This tutorial assumes that the code normally gets built into a container and has a Dockerfile file in the current folder.
If you already have a Docker Compose file for your service(s) you can use it directly. Here is a tutorial that shows you a simple example of how to deploy a node.js service using a Docker Compose file and a single js file.
Step 1 - Create main.js
Let's create a simple node.js service which listens on port 3000 and returns a welcome message. Create a file called main.js
with the following content:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Welcome to Defang\n');
});
server.listen(3000, '0.0.0.0', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
Step 2 - Create Dockerfile
Let's create a Dockerfile to build the node.js service. We'll use the official Node runtime based on Alpine as a parent image. Create a file called Dockerfile
with the following content:
# Use an official Node runtime based on Alpine as a parent image
FROM node:18-alpine
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . .
# Run the app when the container launches
ENTRYPOINT [ "node", "main.js" ]
Step 3 - Create compose.yaml
Let's create a Compose file to deploy the node.js service. We'll call the service minimal and expose port 3000. Create a file called compose.yaml
with the following content:
version: '3.9'
services:
minimal:
build:
context: .
dockerfile: Dockerfile
ports:
- mode: ingress
target: 3000
Step 4 - Deploy
Now that we have the code and the Docker Compose file, we can deploy the service using the defang compose up
command. This will bundle the code into a container and deploy it with Defang. If you have cloud credentials configured, the service will be deployed to AWS. If you don't have AWS credentials set up, the service will be deployed to Defang Playground.
defang compose up