Knocking and pinging is generally caused by improper combustion in your engine, called "auto-ignition."
An internal combustion engine runs properly when the spark-initiated combustion wave expands rapidly but smoothly across the combustion chamber.
If the gasoline-air mixture auto-ignites somewhere in the cylinder (other than at the spark plug) just after spark ignition, the auto-ignition combustion wave can interact with the spark-initiated combustion wave, causing the vibration we hear as a knock or ping.
Increasing engine load, temperature, compression, spark-advance, air-fuel ratio, combustion chamber deposits, and decreasing altitude all increase the tendency for an engine to knock.