Container web server
Learn about how to run a web server inside your Actor, which enables you to communicate with the outer world via both UI and API.
Each Actor run is assigned a unique hard-to-guess URL (e.g. kmdo7wpzlshygi.runs.apify.net
), which enables HTTP access to an optional web server running inside the Actor run's Docker container. The URL is available in the following places:
- In the web application, on the Actor run details page as the Container URL field.
- In the API as the
containerUrl
property of the Run object. - In the Actor run's container as the
ACTOR_WEB_SERVER_URL
environment variable.
The web server running inside the container must listen at the port defined by the ACTOR_WEB_SERVER_PORT
environment variable (typically 4321). If you want to use another port, simply define the ACTOR_WEB_SERVER_PORT
environment variable with the desired port number in your Actor version configuration - see Custom environment variables for details.
The following example demonstrates how to start a simple web server in your Actor:
- JavaScript
- Python
// npm install express
import { Actor } from 'apify';
import express from 'express';
await Actor.init();
const app = express();
const port = process.env.ACTOR_WEB_SERVER_PORT;
app.get('/', (req, res) => {
res.send('Hello world from Express app!');
});
app.listen(port, () => console.log(`Web server is listening
and can be accessed at
${process.env.ACTOR_WEB_SERVER_URL}!`));
// Let the Actor run for an hour
await new Promise((r) => setTimeout(r, 60 * 60 * 1000));
await Actor.exit();
# pip install flask
import asyncio
import os
from apify import Actor
from apify_shared.consts import ActorEnvVars
from flask import Flask
async def main():
async with Actor:
# Create a Flask app
app = Flask(__name__)
# Define a route
@app.route('/')
def hello_world():
return 'Hello world from Flask app!'
# Log the public URL
url = os.environ.get(ActorEnvVars.WEB_SERVER_URL)
Actor.log.info(f'Web server is listening and can be accessed at {url}')
# Start the web server
port = os.environ.get(ActorEnvVars.WEB_SERVER_PORT)
app.run(host='0.0.0.0', port=port)