Main Content

Create Microservice Docker Image

Supported platform: Linux®, Windows®, macOS

This example shows how to create a microservice Docker® image. The microservice image created by MATLAB® Compiler SDK™ provides an HTTP/HTTPS endpoint to access MATLAB code.

You package a MATLAB function into a deployable code archive, and then create a Docker image that contains the archive and a minimal MATLAB Runtime package. You can then run the image in Docker and make calls to the service using any programming language that has HTTP libraries, including MATLAB Production Server™ client APIs.

This option is best for developers who want to incorporate a MATLAB algorithm or Simulink® simulation within a larger application as a service​, or to provide a synchronous request-response backend API service. To create a Docker image that contains a standalone application, see Package MATLAB Standalone Applications into Docker Images.

Prerequisites

Note

Some deployable archives, such as Simulink Compiler™ artifacts, are not cross-platform compatible and must be built on Linux to use with Docker. For more information, see Limitations.

Create MATLAB Function

In MATLAB, examine the MATLAB program that you want to package.

For this example, write a function named mymagic.m using the following code.

function y = mymagic(x)
y = magic(x);

At the MATLAB command prompt, enter mymagic(5).

The output is a 5-by-5 magic square matrix.

ans =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

Create Deployable Archive

Package the mymagic function into a code archive using the compiler.build.productionServerArchive function.

Specify additional options in the compiler.build command by using name-value arguments. For details, see compiler.build.productionServerArchive.

Optionally, you can add a function signature file to help clients use your MATLAB functions. For more details, see MATLAB Function Signatures in JSON.

mpsResults = compiler.build.productionServerArchive('mymagic.m',...
'FunctionSignatures','mymagicFunctionSignatures.json',...
'ArchiveName','magicarchive','Verbose','on')
mpsResults = 

  Results with properties:

                  BuildType: 'productionServerArchive'
                      Files: {'/home/mluser/Work/magicarchiveproductionServerArchive/magicarchive.ctf'}
    IncludedSupportPackages: {}
                    Options: [1×1 compiler.build.ProductionServerArchiveOptions]

The compiler.build.Results object mpsResults contains information on the build type, generated files, included support packages, and build options.

Once the build is complete, the function creates a folder named magicarchiveproductionServerArchive in your current directory that contains the deployable archive.

Package Deployable Archive into Docker Image

Build the microservice Docker image using the mpsResults object that you created.

Specify additional options in the compiler.build command by using name-value arguments. For details, see compiler.package.microserviceDockerImage.

compiler.package.microserviceDockerImage(mpsResults,'ImageName','micro-magic')

The function generates the following files within a folder named micro-magicmicroserviceDockerImage:

  • applicationFilesForMATLABCompiler/magicarchive.ctf — Deployable code archive file.

  • Dockerfile — Docker file that specifies run-time options.

  • GettingStarted.txt — Text file that contains deployment information.

Test Docker Image

Note

If Docker is running in a WSL2 session, preface the following commands with wsl.

  1. In a Linux terminal, verify that your micro-magic image is in your list of Docker images.

    docker images
    REPOSITORY                                      TAG           IMAGE ID            CREATED             SIZE
    micro-magic                                     latest        4401fa2bc057        23 seconds ago      1.42GB
    matlabruntime/r2024a/update0/4200000000000000   latest        5259656e4a32        24 hours ago        1.42GB
  2. Run the micro-magic microservice image in Docker.

    docker run --rm -p 9900:9910 micro-magic

    Port 9910 is the default port exposed by the microservice within the Docker container. You can map it to any available port on your host machine. For this example, it is mapped to port 9900.

    You can specify additional options in the Docker command. For a complete list of options, see Microservice Command Arguments.

  3. Once the container is running in Docker, you can check the status of the service by opening the following URL in a web browser:

    http://hostname:9900/api/health

    Note

    Use localhost as the hostname if Docker is running on the same machine as the browser.

    If the service is ready to receive requests, you see the following message:

    "status:  ok"
  4. Test the running service. In the terminal, use the curl command to send a JSON query with the input argument 4 to the service through port 9900. For more information on constructing JSON requests, see JSON Representation of MATLAB Data Types (MATLAB Production Server).

    curl -v -H Content-Type:application/json -d '{"nargout":1,"rhs":[4]}' \
    "http://hostname:9900/magicarchive/mymagic"

    The output is:

    {"lhs":[{"mwdata":[16,5,9,4,2,11,7,14,3,10,6,15,13,8,12,1],\
    "mwsize":[4,4],"mwtype":"double"}]}

    Note

    To use curl on Windows, use the following syntax:

    curl -v -H Content-Type:application/json -d "{\"nargout\":1,\"rhs\":[4]}" \
    "http://hostname:9900/magicarchive/mymagic"

  5. To stop the service, use the following command to display the container id.

    docker ps
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
    df7710d69bf0        micro-magic         "/opt/matlabruntime/…"   6 minutes ago      Up 6 minutes       0.0.0.0:9900->9910/tcp   epic_herschel
    

    Stop the service using the specified container id.

    docker stop df7710d69bf0

Share Docker Image

You can share your Docker image in various ways.

  • Push your image to the Docker central registry Docker Hub, or to your private registry. This is the most common workflow.

  • Save your image as a tar archive and share it with others. This workflow is suitable for immediate testing.

For details about pushing your image to Docker Hub or your private registry, consult the Docker documentation.

Save Docker Image as Tar Archive

To save your Docker image as a tar archive, open a system command window, navigate to the Docker context folder, and type the following.

docker save micro-magic -o micro-magic.tar

This command creates a file named micro-magic.tar in the current folder. Set the appropriate permissions (for example, using chmod) prior to sharing the tarball with other users.

Load Docker Image from Tar Archive

Load the image contained in the tarball on the end user machine.

docker load --input micro-magic.tar

Verify that the image is loaded.

docker images

Run Docker Image

docker run --rm -p 9900:9910 micro-magic

See Also

|

Related Topics