BLOG POSTS
    MangoHost Blog / How to Set Up Jupyter Notebook with Python 3 on Ubuntu 24
How to Set Up Jupyter Notebook with Python 3 on Ubuntu 24

How to Set Up Jupyter Notebook with Python 3 on Ubuntu 24

Jupyter Notebook has become the go-to tool for data scientists, machine learning engineers, and developers who need an interactive development environment for Python programming. Setting up Jupyter with Python 3 on Ubuntu 24.04 is straightforward, but there are several configuration tweaks and best practices that can save you hours of troubleshooting later. This guide walks you through the complete installation process, from basic setup to advanced configuration options, plus solutions for the most common issues you’ll encounter.

How Jupyter Notebook Works on Ubuntu

Jupyter Notebook runs as a web application that creates a bridge between your browser and a Python kernel running on your system. When you install it on Ubuntu 24.04, you’re essentially setting up a local web server that can execute Python code in isolated cells, display rich output including plots and HTML, and save your work in .ipynb files.

The architecture consists of three main components: the notebook server (handles HTTP requests), the kernel (executes code), and the web interface (your browser). Ubuntu 24.04 ships with Python 3.12 by default, which works perfectly with the latest Jupyter versions. The notebook server typically runs on localhost:8888, but you can configure it to accept remote connections if you’re setting this up on a VPS or dedicated server.

Step-by-Step Installation Guide

First, make sure your Ubuntu 24.04 system is updated and has the necessary tools installed:

sudo apt update && sudo apt upgrade -y
sudo apt install python3 python3-pip python3-venv curl wget -y
python3 --version

The cleanest approach is using a virtual environment to avoid conflicts with system packages. Create and activate a virtual environment:

mkdir ~/jupyter-env
cd ~/jupyter-env
python3 -m venv jupyter_venv
source jupyter_venv/bin/activate

Now install Jupyter Notebook and essential packages. I recommend installing the full Jupyter suite rather than just the basic notebook:

pip install --upgrade pip
pip install jupyter jupyterlab numpy pandas matplotlib seaborn scikit-learn
pip install ipywidgets nbextensions

Enable Jupyter extensions for better functionality:

jupyter nbextension enable --py widgetsnbextension
jupyter lab build

Generate a Jupyter configuration file and set up basic security:

jupyter notebook --generate-config
jupyter notebook password

Start Jupyter Notebook to test the installation:

jupyter notebook

If everything works correctly, Jupyter will open in your browser at http://localhost:8888. For server installations, you’ll need additional configuration to enable remote access safely.

Remote Access Configuration

Setting up Jupyter for remote access requires careful attention to security. Edit the configuration file:

nano ~/.jupyter/jupyter_notebook_config.py

Add these configuration lines:

c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.NotebookApp.allow_root = True
c.NotebookApp.allow_remote_access = True

For production environments, always use HTTPS. Generate SSL certificates:

mkdir ~/.jupyter/ssl
cd ~/.jupyter/ssl
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout jupyter.key -out jupyter.crt

Update the config to use SSL:

c.NotebookApp.certfile = '/home/username/.jupyter/ssl/jupyter.crt'
c.NotebookApp.keyfile = '/home/username/.jupyter/ssl/jupyter.key'

Configure the firewall to allow Jupyter traffic:

sudo ufw allow 8888/tcp
sudo ufw enable

Performance Optimization and Best Practices

Ubuntu 24.04 handles memory management well, but Jupyter can be memory-intensive with large datasets. Monitor resource usage and configure limits:

pip install psutil
jupyter notebook --NotebookApp.max_buffer_size=1073741824
Configuration Default Value Recommended for 4GB RAM Recommended for 8GB RAM
max_buffer_size 536870912 (512MB) 1073741824 (1GB) 2147483648 (2GB)
iopub_data_rate_limit 1000000 10000000 10000000
rate_limit_window 3.0 10.0 10.0

For better performance with large datasets, consider installing additional optimizations:

pip install numba dask[complete]
jupyter labextension install @jupyterlab/toc

Common Issues and Troubleshooting

The most frequent problem is kernel connection issues. If you see “Kernel not found” or connection errors:

jupyter kernelspec list
python -m ipykernel install --user --name=jupyter_venv

Permission problems often occur when switching between root and user accounts. Fix ownership issues:

sudo chown -R $USER:$USER ~/.jupyter
sudo chown -R $USER:$USER ~/.local/share/jupyter

If Jupyter won’t start due to port conflicts, find and kill conflicting processes:

sudo netstat -tulpn | grep :8888
sudo kill -9 [PID]

Memory errors with large datasets can be resolved by increasing swap space:

sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Real-World Use Cases and Examples

Data scientists often need to process CSV files larger than available RAM. Here’s a practical example using chunking:

import pandas as pd
import matplotlib.pyplot as plt

# Process large CSV in chunks
chunk_size = 10000
chunks = []

for chunk in pd.read_csv('large_dataset.csv', chunksize=chunk_size):
    # Process each chunk
    processed_chunk = chunk.groupby('category').sum()
    chunks.append(processed_chunk)

# Combine results
final_result = pd.concat(chunks, ignore_index=True)
final_result.plot(kind='bar')

For machine learning workflows, you can set up automated model training:

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import joblib

# Load and split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# Train model
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)

# Save model
joblib.dump(rf, 'model.pkl')
print(f"Model accuracy: {rf.score(X_test, y_test):.3f}")

Comparison with Alternative Solutions

Solution Installation Complexity Resource Usage Best For
Jupyter Notebook Low Medium Interactive development, prototyping
JupyterLab Low High Advanced workflows, multiple documents
VSCode + Python Medium Low Production code, debugging
Google Colab None N/A (Cloud) Quick experiments, learning

JupyterLab offers a more integrated experience but uses more resources. If you’re running on a resource-constrained system, stick with classic Jupyter Notebook. For production data science workflows on powerful servers, JupyterLab provides better project management capabilities.

Advanced Configuration and Integration

Set up Jupyter as a system service for automatic startup:

sudo nano /etc/systemd/system/jupyter.service

Add the service configuration:

[Unit]
Description=Jupyter Notebook Server
After=network.target

[Service]
Type=simple
User=username
ExecStart=/home/username/jupyter-env/jupyter_venv/bin/jupyter notebook
WorkingDirectory=/home/username
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Enable and start the service:

sudo systemctl daemon-reload
sudo systemctl enable jupyter
sudo systemctl start jupyter

For integration with existing Python projects, you can install project-specific kernels:

cd /path/to/project
python -m venv project_env
source project_env/bin/activate
pip install ipykernel
python -m ipykernel install --user --name=project_env --display-name="Project Environment"

The official Jupyter documentation at https://jupyter.readthedocs.io/en/latest/ provides comprehensive information about advanced features and customization options. For Ubuntu-specific Python development, the Python 3 documentation covers integration details and best practices.

This setup gives you a robust, production-ready Jupyter environment on Ubuntu 24.04 that can handle everything from simple data analysis to complex machine learning workflows. The virtual environment approach ensures clean dependency management, while the security configurations protect your work when accessing notebooks remotely.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked