Main Content

Create Microservice Docker Image

Supported platform: Linux® only

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 compile a MATLAB function into a deployable 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 of the MATLAB Production Server™ client APIs.

This option is best for developers who want to incorporate a MATLAB algorithm or Simulink® simulation as a service within a larger application​, 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

  • Verify that you have MATLAB Compiler SDK installed on a Linux machine.

  • Verify that you have Docker installed on your Linux machine by typing docker in the terminal. If you do not have Docker installed, you can follow the instructions on the Docker website to install and set up Docker.

    https://docs.docker.com/engine/install/

  • Verify that the MATLAB Runtime installer is available on your machine. You can verify its existence by executing the compiler.runtime.download function at the MATLAB command prompt. If there is an existing installer on the machine, the function returns its location. Otherwise, it downloads the MATLAB Runtime installer matching the version and update level of MATLAB from where the command is executed.

    If the computer you are using is not connected to the Internet, you must download the MATLAB Runtime installer from a computer that is connected to the Internet and transfer the installer to the computer that is not connected to the Internet. You can download the installer from the MathWorks website.

    https://www.mathworks.com/products/compiler/matlab-runtime.html

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 deployable archive using the compiler.build.productionServerArchive function.

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

mpsResults = compiler.build.productionServerArchive('mymagic.m', ...
'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 to store the deployable archive.

Package Archive into Microservice Docker Image

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

    You can 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 in your current working directory:

    • applicationFilesForMATLABCompiler/magicarchive.ctf — Deployable archive file.

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

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

Test Docker Image

  1. In a Linux terminal window, 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/r2022a/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 list of options, see Microservice Command Arguments.

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

    http://hostname:9900/api/health

    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"}]}

  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 DockerHub, 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 DockerHub 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 Linux terminal 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 your current folder. Set the appropriate permissions 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's 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