If you plan to bring vetiver to a public or private cloud outside of RStudio Connect, Docker containers are a highly portable solution. Using vetiver makes Dockerfile creation easy by generating the files you need from your trained models.
Import data
For this demo, we will use data from Tidy Tuesday to predict the number of YouTube likes a television commercial played during the Super Bowl will get, based on qualities such as if the ad included any animals, if the ad was funny, if the ad had any elements of danger, etc.
With data in hand, the next step is feature engineering and model estimation. We put these two steps into a single function, such as a pipeline or workflow, and will deploy these pieces together. (Why are we doing this?)
import pinsboard = pins.board_rsconnect( server_url=server_url, # load from an .env file api_key=api_key, # load from an .env file allow_pickle_read=True)vetiver.vetiver_pin_write(board, v)
library(pins)board <-board_rsconnect() # authenticates via environment variablesvetiver_pin_write(board, v)
Here we are using board_rsconnect(), but you can use other boards such as board_s3(). Read more about how to store and version your vetiver model.
Create API and Docker artifacts
Next, let’s create an app.py or plumber.R file. This file contains the information to create a vetiver REST API and will be running inside your Docker container.
Once you have this file, vetiver can help you write a Dockerfile.
vetiver.write_app( board, "isabel.zimmerman/superbowl_rf", version ="20220901T144702Z-fd402")vetiver.write_docker()
Note
You may need to edit the app.py file to load a .env file for authorization, if necessary.
Docker also needs a requirements file. You can generate your own, or use vetiver.load_pkgs() to generate a file named vetiver_req.txt with the packages necessary for prediction.
When you run vetiver_write_docker(), you generate two files: the Dockerfile itself and the vetiver_renv.lock file to capture your model dependencies.
You have now created all the artifacts to run your Docker container!
Build and run your Dockerfile
It is time to build and run your container. Building the Docker container can potentially take a while, because it installs all the packages needed to make a prediction with this model. Use the command line (not R or Python) to build your Docker container:
docker build -t superbowlads .
Tip
If you are on an ARM architecture locally and deploying an R model, use --platform linux/amd64 for RSPM’s fast installation of binaries.
Now run! To authenticate to your board (to get the pinned vetiver model from, for example, RStudio Connect), pass in a file supplying environment variables.
docker run --env-file .env -p 8080:8080 superbowlads
Tip
R users likely will store their environment variables in a file called .Renviron instead of .env.
The Docker container is now running locally! You can interact with it, such as by using a browser to visit http://0.0.0.0:8080/__docs__/