Prerequisites : docker configured and running, curl
In this tutorial we will explore how we can create a docker container which has a Ballerina service embedded within. Ballerina supports dockerizing out of the box. Here is how you can achieve this.
Method 01 : Creating your own docker image
- First download the ballerina tools distribution. The latest ballerina pack can be found at : https://ballerinalang.org/downloads/
- Extract the downloaded zip and set up ballerina runtime.
- Now create a ballerina service to be added to the docker container. You can create the following service. (You can also create a main function as well) Name the file, docker-service.bal
import ballerina.net.http;
@http:configuration {basePath:"/echo"}
service<http> echo {
@http:resourceConfig {
methods:["POST"],
path:"/"
}
resource echo (http:Request req, http:Response resp) {
string payload = req.getStringPayload();
resp.setStringPayload(payload);
resp.send();
}
}
- Create the docker image with the following command.
ballerina docker docker-service.bal
If the above command succeeds you will see something like below.
To verify image creation execute the following command which will list all the images in local docker registry.
docker images
7. Start the container with the following command.
docker run -p 39165:9090 --name docker-sample -d docker-service:latest
8. The service should be up and running. You can verify this by listing all the docker processes.
docker ps
9. Invoke the service with following command.
curl -X POST http://localhost:39165/echo -d 'This is a sample message'
If everything is successful, you will see the echoed response from the ballerina server.
Method 2 : Adding your services to existing docker container
The Docker distribution for Ballerina is available on Docker Hub as ballerinalang/ballerina. To run a Ballerina package using the Ballerina Docker image, simply mount the folder containing the file to /ballerina/files folder inside the container. Following is how you can do this.
- First pull the ballerina docker image.
docker pull ballerinalang/ballerina
- Create a directory and copy the packages needed to be run.
mkdir -p ~/ballerina/service/
- Add the following service to ~/ballerina/service
import ballerina.net.http;
@http:configuration {basePath:"/echo"}
service<http> echo {
@http:resourceConfig {
methods:["POST"],
path:"/"
}
resource echo (http:Request req, http:Response resp) {
string payload = req.getStringPayload();
resp.setStringPayload(payload);
resp.send();
}
}
- Mount the volume and start the docker container
docker run -v ~/ballerina/service:/ballerina/files -p 9090:9090 -it ballerinalang/ballerina:0.95.0
5. Now invoke the service with following curl command.
curl -X POST http://localhost:9090/echo -d 'This is a sample message'
If everything is successful, you will see the echoed response from the ballerina server
0 comments:
Post a Comment